Cookie的使用
学号:201631062509
姓名:杨菓
1.Cookie的概念
cookie 历来指就着牛奶一起吃的点心。然而,在因特网内,“cookie”这个字有了完全不同的意思。那么“cookie”到底是什么呢?“Cookie”是小量信息,由网络服务器发送出来以存储在网络浏览器上,从而下次这位独一无二的访客又回到该网络服务器时,可从该浏览器读回此信息。这是很有用的,让浏览器记住这位访客的特定信息,如上次访问的位置、花费的时间或用户首选项(如样式表)。Cookie 是个存储在浏览器目录的文本文件,当浏览器运行时,存储在 RAM 中。一旦阁下从该网站或网络服务器退出,Cookie 也可存储在计算机的硬驱上。当访客结束其浏览器对话时,即终止的所有 cookie。Cookie 的用途之一是存储用户在特定网站上的密码和 ID。另外,也用于存储起始页的首选项。在提供个人化查看的网站上,将要求阁下的网络浏览器利用阁下计算机硬驱上的少量空间来储存这些首选项。这样,每次阁下登录该网站时,阁下的浏览器将检查阁下是否就该唯一的服务器有任何预先定义的首选项(cookie)。如果有的话,浏览器将此 cookie 随阁下对网页的请求一起发送给服务器。Microsoft 和 Netscape 使用 cookie 在其网站上创建个人起始页。各家公司利用 cookie 的一般用途包括:在线定货系统、网站个人化和网站跟踪。网站个人化是 cookie 最有益的用途之一。例如,当谁来到 CNN 网站,但并不想查看任何商务新闻。网站允许他将该项选为选项。从那时起(或者直到 cookie 逾期),他在访问 CNN 网页时将不会读到商务新闻。
工作原理:要了解Cookie,必不可少地要知道它的工作原理。一般来说,Cookie通过HTTP Headers从服务器端返回到浏览器上。首先,服务器端在响应中利用Set-Cookie header来创建一个Cookie ,然后,浏览器在它的请求中通过Cookie header包含这个已经创建的Cookie,并且把它返回至服务器,从而完成浏览器的论证。例如,我们创建了一个名字为login的Cookie来包含访问者的信息,创建Cookie时,服务器端的Header如下面所示,这里假设访问者的注册名是“Michael Jordan”,同时还对所创建的Cookie的属性如pathdomain、expires等进行了指定。expires=Monday,01-Mar-99 00:00:01 GMT上面这个Header会自动在浏览器端计算机的Cookie文件中添加一条记录。浏览器将变量名为“login”的Cookie赋值为“Michael Jordon”。注意,在实际传递过程中这个Cookie的值是经过了URLEncode方法的URL编码操作的。这个含有Cookie值的HTTP Header被保存到浏览器的Cookie文件后,Header就通知浏览器将Cookie通过请求以忽略路径的方式返回到服务器,完成浏览器的认证操作。此外,我们使用了Cookie的一些属性来限定该Cookie的使用。例如Domain属性能够在浏览器端对Cookie发送进行限定,具体到上面的例子,该Cookie只能传送到指定的服务器上,而决不会跑到其他的如的Web站点上去。Expires属性则指定了该Cookie保存的时间期限,例如上面的Cookie在浏览器上只保存到1999年3月1日1秒。当然,如果浏览器上Cookie 太多,超过了系统所允许的范围,浏览器将自动对它进行删除。至于属性Path,用来指定Cookie将被发送到服务器的哪一个目录路径下。说明:浏览器创建了一个Cookie后,对于每一个针对该网站的请求,都会在Header中带着这个Cookie;不过,对于其他网站的请求Cookie是绝对不会跟着发送的。而且浏览器会这样一直发送,直到Cookie过期为止。
2.效果图
主界面图
未登录的时候,显示跳转页面
输入用户名密码
登录成功
实现自动登录成功
3.源代码
Cookie
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.io.IOException; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.Cookie; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 /** 11 * Servlet implementation class indexPage 12 */ 13 @WebServlet("/indexPage") 14 public class indexPage extends HttpServlet { 15 private static final long serialVersionUID = 1L; 16 17 /** 18 * @see HttpServlet#HttpServlet() 19 */ 20 public indexPage() { 21 super(); 22 // TODO Auto-generated constructor stub 23 } 24 25 /** 26 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 27 */ 28 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 29 // TODO Auto-generated method stub 30 boolean alreadyHave = false; 31 32 request.setCharacterEncoding("UTF-8"); 33 response.setContentType("text/html;charset=UTF-8"); 34 35 36 Cookie[] cookies = request.getCookies(); 37 if(cookies != null){ 38 for(int i = 0; i < cookies.length; ++i){ 39 if(cookies[i].getName().equals("user")){ 40 response.getWriter().write(cookies[i].getValue()+",您已登录!"); 41 response.getWriter().write("<br/><a href="+"LoginPage.html"+">重新登录</a>"); 42 alreadyHave = true; 43 } 44 } 45 } 46 47 if(alreadyHave == false){ 48 response.getWriter().write("五秒后跳转登录页面"); 49 response.setHeader("refresh", "3;url=LoginPage.html"); 50 } 51 } 52 53 /** 54 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 55 */ 56 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 57 // TODO Auto-generated method stub 58 doGet(request, response); 59 } 60 61 } 62 63 64 import java.io.IOException; 65 import java.sql.*; 66 import java.util.List; 67 68 import javax.servlet.ServletException; 69 import javax.servlet.annotation.WebServlet; 70 import javax.servlet.http.Cookie; 71 import javax.servlet.http.HttpServlet; 72 import javax.servlet.http.HttpServletRequest; 73 import javax.servlet.http.HttpServletResponse; 74 75 import DaoUtils.JdbcUtils; 76 77 78 79 /** 80 * Servlet implementation class check 81 */ 82 @WebServlet("/check") 83 public class check extends HttpServlet { 84 private static final long serialVersionUID = 1L; 85 86 /** 87 * @see HttpServlet#HttpServlet() 88 */ 89 public check() { 90 super(); 91 // TODO Auto-generated constructor stub 92 } 93 94 /** 95 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 96 */ 97 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 98 // TODO Auto-generated method stub 99 100 Connection con = null; 101 PreparedStatement preparedStatement = null; 102 ResultSet rs = null; 103 104 request.setCharacterEncoding("UTF-8"); 105 response.setContentType("text/html;charset=UTF-8"); 106 107 108 String userName = request.getParameter("checkInID"); 109 String userPass = request.getParameter("checkInPass"); 110 111 try { 112 con = JdbcUtils.getConnection(); 113 String sql = "SELECT * FROM USER WHERE userName = '" + userName + "' AND userPass = " + userPass; 114 preparedStatement = con.prepareStatement("SELECT * FROM USER WHERE userName = ? AND userPass = ?"); 115 preparedStatement.setString(1, userName); 116 preparedStatement.setInt(2, Integer.valueOf(userPass)); 117 rs = preparedStatement.executeQuery(); 118 if(!rs.next()){ 119 response.getWriter().write("用户名或密码错误"); 120 }else{ 121 if(request.getParameterValues("remembered")!= null && request.getParameterValues("remembered")[0]!=null){ 122 123 Cookie cookie = new Cookie("user", userName); 124 cookie.setMaxAge(3600); 125 response.addCookie(cookie); 126 }else{ 127 Cookie cookie = new Cookie("user", userName); 128 cookie.setMaxAge(0);//删除cookie 129 response.addCookie(cookie); 130 } 131 response.getWriter().write("登陆成功</br>"); 132 response.getWriter().write("用户名:" + rs.getString(1)); 133 response.getWriter().write("</br>"); 134 response.getWriter().write("密码:" + rs.getInt(2)); 135 } 136 137 } catch (SQLException | ClassNotFoundException e) { 138 // TODO 自动生成的 catch 块 139 e.printStackTrace(); 140 } finally { 141 release(con, preparedStatement, rs); 142 } 143 } 144 145 /** 146 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 147 */ 148 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 149 // TODO Auto-generated method stub 150 doGet(request, response); 151 } 152 153 public static void release(Connection conn, Statement st, ResultSet rs){ 154 if(rs != null){ 155 try{ 156 rs.close(); 157 }catch (Exception e) { 158 // TODO: handle exception 159 e.printStackTrace(); 160 } 161 162 rs = null; 163 } 164 165 if(st != null){ 166 try{ 167 st.close(); 168 }catch (Exception e) { 169 // TODO: handle exception 170 e.printStackTrace(); 171 } 172 173 st = null; 174 } 175 176 if(conn != null){ 177 try{ 178 conn.close(); 179 }catch (Exception e) { 180 // TODO: handle exception 181 e.printStackTrace(); 182 } 183 184 conn = null; 185 } 186 } 187 188 }
HTML
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.io.IOException; 2 import java.sql.*; 3 import java.util.List; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.Cookie; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import DaoUtils.JdbcUtils; 13 14 15 16 /** 17 * Servlet implementation class check 18 */ 19 @WebServlet("/check") 20 public class check extends HttpServlet { 21 private static final long serialVersionUID = 1L; 22 23 /** 24 * @see HttpServlet#HttpServlet() 25 */ 26 public check() { 27 super(); 28 // TODO Auto-generated constructor stub 29 } 30 31 /** 32 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 33 */ 34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 // TODO Auto-generated method stub 36 37 Connection con = null; 38 PreparedStatement preparedStatement = null; 39 ResultSet rs = null; 40 41 request.setCharacterEncoding("UTF-8"); 42 response.setContentType("text/html;charset=UTF-8"); 43 44 45 String userName = request.getParameter("checkInID"); 46 String userPass = request.getParameter("checkInPass"); 47 48 try { 49 con = JdbcUtils.getConnection(); 50 String sql = "SELECT * FROM USER WHERE userName = '" + userName + "' AND userPass = " + userPass; 51 preparedStatement = con.prepareStatement("SELECT * FROM USER WHERE userName = ? AND userPass = ?"); 52 preparedStatement.setString(1, userName); 53 preparedStatement.setInt(2, Integer.valueOf(userPass)); 54 rs = preparedStatement.executeQuery(); 55 if(!rs.next()){ 56 response.getWriter().write("用户名或密码错误"); 57 }else{ 58 if(request.getParameterValues("remembered")!= null && request.getParameterValues("remembered")[0]!=null){ 59 60 Cookie cookie = new Cookie("user", userName); 61 cookie.setMaxAge(3600); 62 response.addCookie(cookie); 63 }else{ 64 Cookie cookie = new Cookie("user", userName); 65 cookie.setMaxAge(0);//删除cookie 66 response.addCookie(cookie); 67 } 68 response.getWriter().write("登陆成功</br>"); 69 response.getWriter().write("用户名:" + rs.getString(1)); 70 response.getWriter().write("</br>"); 71 response.getWriter().write("密码:" + rs.getInt(2)); 72 } 73 74 } catch (SQLException | ClassNotFoundException e) { 75 // TODO 自动生成的 catch 块 76 e.printStackTrace(); 77 } finally { 78 release(con, preparedStatement, rs); 79 } 80 } 81 82 /** 83 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 84 */ 85 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 86 // TODO Auto-generated method stub 87 doGet(request, response); 88 } 89 90 public static void release(Connection conn, Statement st, ResultSet rs){ 91 if(rs != null){ 92 try{ 93 rs.close(); 94 }catch (Exception e) { 95 // TODO: handle exception 96 e.printStackTrace(); 97 } 98 99 rs = null; 100 } 101 102 if(st != null){ 103 try{ 104 st.close(); 105 }catch (Exception e) { 106 // TODO: handle exception 107 e.printStackTrace(); 108 } 109 110 st = null; 111 } 112 113 if(conn != null){ 114 try{ 115 conn.close(); 116 }catch (Exception e) { 117 // TODO: handle exception 118 e.printStackTrace(); 119 } 120 121 conn = null; 122 } 123 } 124 125 }
Servlet
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.io.IOException; 2 import java.sql.*; 3 import java.util.List; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 import DaoUtils.JdbcUtils; 12 13 14 15 /** 16 * Servlet implementation class check 17 */ 18 @WebServlet("/check") 19 public class check extends HttpServlet { 20 private static final long serialVersionUID = 1L; 21 22 /** 23 * @see HttpServlet#HttpServlet() 24 */ 25 public check() { 26 super(); 27 // TODO Auto-generated constructor stub 28 } 29 30 /** 31 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 32 */ 33 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 34 // TODO Auto-generated method stub 35 36 Connection con = null; 37 PreparedStatement preparedStatement = null; 38 ResultSet rs = null; 39 40 request.setCharacterEncoding("UTF-8"); 41 response.setContentType("text/html;charset=UTF-8"); 42 43 String userName = request.getParameter("checkInID"); 44 String userPass = request.getParameter("checkInPass"); 45 46 try { 47 con = JdbcUtils.getConnection(); 48 String sql = "SELECT * FROM USER WHERE userName = '" + userName + "' AND userPass = " + userPass; 49 preparedStatement = con.prepareStatement("SELECT * FROM USER WHERE userName = ? AND userPass = ?"); 50 preparedStatement.setString(1, userName); 51 preparedStatement.setInt(2, Integer.valueOf(userPass)); 52 rs = preparedStatement.executeQuery(); 53 54 if(!rs.next()){ 55 response.getWriter().write("用户名或密码错误"); 56 }else{ 57 58 response.getWriter().write("用户名:" + rs.getString(1)); 59 response.getWriter().write("</br>"); 60 response.getWriter().write("密码:" + rs.getInt(2)); 61 } 62 63 } catch (SQLException | ClassNotFoundException e) { 64 // TODO 自动生成的 catch 块 65 e.printStackTrace(); 66 } finally { 67 release(con, preparedStatement, rs); 68 } 69 70 } 71 72 /** 73 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 74 */ 75 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 76 // TODO Auto-generated method stub 77 doGet(request, response); 78 } 79 80 public static void release(Connection conn, Statement st, ResultSet rs){ 81 if(rs != null){ 82 try{ 83 rs.close(); 84 }catch (Exception e) { 85 // TODO: handle exception 86 e.printStackTrace(); 87 } 88 89 rs = null; 90 } 91 92 if(st != null){ 93 try{ 94 st.close(); 95 }catch (Exception e) { 96 // TODO: handle exception 97 e.printStackTrace(); 98 } 99 100 st = null; 101 } 102 103 if(conn != null){ 104 try{ 105 conn.close(); 106 }catch (Exception e) { 107 // TODO: handle exception 108 e.printStackTrace(); 109 } 110 111 conn = null; 112 } 113 } 114 115 }
CSS
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 .h{ 2 width: 964px; 3 margin: 0 auto; 4 } 5 *{ 6 margin: 0; 7 padding: 0; 8 } 9 .t{ 10 height: 95px; 11 line-height: 90px; 12 background-color:#f5f5f5 ; 13 border-bottom-width: 1px; 14 border-bottom-style: solid; 15 border-bottom-color: #e5ecf0; 16 overflow:hidden; 17 } 18 .logo{ 19 padding-top: 15px; 20 float: left; 21 } 22 .help{ 23 float: right; 24 font-size: 14px; 25 font-weight: 700; 26 color: #787878; 27 text-decoration: none; 28 } 29 body{ 30 font-family: "微软雅黑",verdana,geneva,sans-serif; 31 font-size: 12px; 32 background: #fff; 33 } 34 .box{ 35 width: 376px; 36 position: absolute; 37 box-shadow: 0px 0px 5px rgba(0,0,0,0,4); 38 } 39 .c{ 40 width: 964px; 41 height: 460px; 42 margin: 20px auto 0 auto; 43 background: url(../img/backimg.png) no-repeat; 44 background-attachment: scroll; 45 background-repeat: no-repeat; 46 background-position-x: 0%; 47 background-position-y: 0%; 48 background-size: cover; 49 background-origin: padding-box; 50 background-clip: border-box; 51 background-color: transparent; 52 position: relative; 53 } 54 .tab li.current{ 55 background-attachment: scroll; 56 background-repeat: repeat; 57 background-size: auto; 58 background: #ff7e00; 59 } 60 .tab li.dragbar{ 61 width: 22px; 62 cursor: move; 63 overflow: hidden; 64 } 65 .tab li{ 66 height: 40px; 67 line-height: 40px; 68 float: left; 69 width: 354px; 70 text-align: center; 71 background: #333; 72 color: #fff; 73 font-size: 16px; 74 cursor: pointer; 75 } 76 .msg{ 77 position: absolute; 78 background: #cc3300; 79 color: #FFFFFF; 80 padding: 0 10px; 81 font-size: 14px; 82 } 83 ul{ 84 list-style-type: none; 85 list-style-position: outside; 86 list-style-image: none; 87 } 88 .tab{ 89 border-bottom: 3px solid rgba(255,126,0,0.8); 90 overflow: hidden; 91 } 92 .boxc{ 93 background: #FFFFFF; 94 padding: 20px 0 30px 42px; 95 } 96 .text{ 97 height: 36px; 98 line-height: 36px; 99 outline: none; 100 width: 280px; 101 border: 1px solid #c7c7c7; 102 background: #f3f3f3; 103 border-radius: 1px; 104 padding: 0 5px; 105 font-family: "微软雅黑"; 106 } 107 .text_item{ 108 height: 38px; 109 line-height: 38px; 110 width: 292px; 111 margin: 15px 0 30px 0; 112 } 113 .btnb{ 114 margin: 20px 0 0 0; 115 width: 292px; 116 position: relative; 117 } 118 .btn{ 119 height: 38px; 120 width: 142px; 121 border: none; 122 color: #fff; 123 font-weight: 400; 124 font-size:20px; 125 font-family: "微软雅黑"; 126 } 127 .nouser{ 128 position: absolute; 129 background: #CC3300; 130 color: #fff; 131 padding: 0 10px; 132 font-size: 14px; 133 height: 30px; 134 line-height: 30px; 135 left: 42px; 136 right: 42px; 137 text-align: center; 138 display: none; 139 }
JDBC
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package DaoUtils; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.ResultSet; 8 import java.sql.SQLException; 9 import java.sql.Statement; 10 import java.util.Properties; 11 12 13 public class JdbcUtils { 14 private static String driver = null; 15 private static String url = null; 16 private static String username = null; 17 private static String password = null; 18 19 public static void setDriver(String driver) { 20 JdbcUtils.driver = driver; 21 } 22 23 public static void setPassword(String password) { 24 JdbcUtils.password = password; 25 } 26 27 public static void setUsername(String username) { 28 JdbcUtils.username = username; 29 } 30 31 public static void setUrl(String url) { 32 JdbcUtils.url = url; 33 } 34 35 public static String getDriver() { 36 return driver; 37 } 38 39 public static String getPassword() { 40 return password; 41 } 42 43 public static String getUrl() { 44 return url; 45 } 46 47 public static String getUsername() { 48 return username; 49 } 50 51 static{ 52 //try{ 53 /*String driver = "com.mysql.jdbc.Driver"; 54 String url = "jdbc:mysql://localhost:3306/checkprojectdb"; 55 String username = "root"; 56 String password = "980420";*/ 57 58 Properties p = new Properties(); 59 try{ 60 //通过相对路径加载文件 61 String path = (Thread.currentThread().getContextClassLoader().getResource("").getFile()).substring(1); 62 path=java.net.URLDecoder.decode(path, "utf-8"); 63 path=path.replace('/', '\'); 64 path=path.replace("file:", ""); 65 path=path.replace("classes\", ""); 66 path+="classes/DaoUtils/db.properties"; 67 p.load(new FileInputStream(new File(path))); 68 //用getProperties方法通过关键字获取信息 69 driver = p.getProperty("driver"); 70 url = p.getProperty("url"); 71 username = p.getProperty("username"); 72 password = p.getProperty("password"); 73 //} 74 Class.forName(driver); 75 }catch (Exception e) { 76 // TODO: handle exception 77 System.out.println(driver +" " + url + " " + username +" " + password ); 78 throw new ExceptionInInitializerError(e); 79 } 80 } 81 82 public static Connection getConnection() throws SQLException, ClassNotFoundException{ 83 return DriverManager.getConnection(url, username, password); 84 } 85 86 public static void release(Connection conn, Statement st, ResultSet rs){ 87 if(rs != null){ 88 try{ 89 rs.close(); 90 }catch (Exception e) { 91 // TODO: handle exception 92 e.printStackTrace(); 93 } 94 95 rs = null; 96 } 97 98 if(st != null){ 99 try{ 100 st.close(); 101 }catch (Exception e) { 102 // TODO: handle exception 103 e.printStackTrace(); 104 } 105 106 st = null; 107 } 108 109 if(conn != null){ 110 try{ 111 conn.close(); 112 }catch (Exception e) { 113 // TODO: handle exception 114 e.printStackTrace(); 115 } 116 117 conn = null; 118 } 119 } 120 121 public static void main(String[] args) { 122 System.out.println(driver + "; " + username + "; " + password + "; " + url); 123 } 124 }
JS
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 function checkForm(){ 2 var subButton = document.getElementById("subBut"); 3 var userID = document.getElementById("checkInID"); 4 var userP = document.getElementById("checkInPass"); 5 6 if(userID.value == "" || userP.value == ""){ 7 var info = document.getElementById("login-info"); 8 var infoStyle = info.style; 9 infoStyle.visibility = "visible"; 10 info.innerText = "请输入用户名"; 11 return false; 12 }else{ 13 return true; 14 } 15 }
4.百度云地址
链接:https://pan.baidu.com/s/1AMv5X5oxfkEfkf2W0joINA
提取码:l8je