Cookie:
使用Cookie机制实现十天内免登陆:
Servlet程序:
1 package com.bjpowernode.javaweb.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.PreparedStatement; 8 import java.sql.ResultSet; 9 import java.sql.SQLException; 10 11 import javax.servlet.ServletException; 12 import javax.servlet.http.Cookie; 13 import javax.servlet.http.HttpServlet; 14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletResponse; 16 17 /** 18 * 检查登录时服务器是否接收到前端页面发送的Cookie, 19 * 若收到则直接登录,登录成功则跳转到成功页面,登录失败则跳转到失败页面, 20 * 若没收到则再跳转到登录页面 21 * @author qjj 22 * 23 */ 24 public class CheckLoginStatusServlet extends HttpServlet { 25 26 private static final long serialVersionUID = 1L; 27 28 @Override 29 protected void doGet(HttpServletRequest request, HttpServletResponse response) 30 throws ServletException, IOException { 31 //从request中获取所有的Cookie 32 Cookie[] cookies = request.getCookies(); 33 String username = null; 34 String password = null; 35 if(cookies != null){ 36 //遍历Cookie 37 for(Cookie cookie : cookies){ 38 String cookieName = cookie.getName(); 39 String cookieValue = cookie.getValue(); 40 if("username".equals(cookieName)){ 41 username = cookieValue; 42 }else if("password".equals(cookieName)){ 43 password = cookieValue; 44 } 45 } 46 } 47 48 if(username != null && password != null){ 49 //接收到Cookie 50 //连接数据库验证用户名和密码 51 Connection conn = null; 52 PreparedStatement ps = null; 53 ResultSet rs = null; 54 boolean loginSuccess = false; 55 String realName = null; 56 try{ 57 Class.forName("com.mysql.jdbc.Driver"); 58 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "root", "248xiaohai"); 59 String sql = "select id,username,password,realname from t_user where username=? and password=?"; 60 ps = conn.prepareStatement(sql); 61 ps.setString(1, username); 62 ps.setString(2, password); 63 rs = ps.executeQuery(); 64 if(rs.next()){ 65 loginSuccess = true; 66 realName = rs.getString("realname"); 67 } 68 } catch (Exception e) { 69 e.printStackTrace(); 70 } finally { 71 if(rs != null){ 72 try { 73 rs.close(); 74 } catch (SQLException e) { 75 e.printStackTrace(); 76 } 77 } 78 if(ps != null){ 79 try { 80 ps.close(); 81 } catch (SQLException e) { 82 e.printStackTrace(); 83 } 84 } 85 if(conn != null){ 86 try { 87 conn.close(); 88 } catch (SQLException e) { 89 e.printStackTrace(); 90 } 91 } 92 } 93 //登录成功跳转到成功页面,失败跳转到失败页面 94 if(loginSuccess){ 95 //这里的成功页面已响应的方式发送到前端,是因为有动态参数realname的存在,之后学了JSP就不用这么写了 96 response.setContentType("text/html;charset=UTF-8"); 97 PrintWriter out = response.getWriter(); 98 out.print("<html>"); 99 out.print("<head>"); 100 out.print("<title>欢迎页面</title>"); 101 out.print("</head>"); 102 out.print("<body>"); 103 out.print("欢迎"); 104 out.print(realName); 105 out.print("访问"); 106 out.print("</body>"); 107 out.print("</html>"); 108 }else{ 109 response.sendRedirect(request.getContextPath() + "/login_error.html"); 110 } 111 }else{ 112 //没接收到Cookie,则跳转到登录页面 113 response.sendRedirect(request.getContextPath() + "/login.html"); 114 } 115 } 116 117 118 }
1 package com.bjpowernode.javaweb.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.PreparedStatement; 8 import java.sql.ResultSet; 9 import java.sql.SQLException; 10 11 import javax.servlet.ServletException; 12 import javax.servlet.http.Cookie; 13 import javax.servlet.http.HttpServlet; 14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletResponse; 16 17 /** 18 * 登录页面的响应,登录成功先判断是否选择十天内免登录,若选择则先向浏览器发送Cookie, 19 * 然后跳转到成功页面 20 * 若登录失败,则跳转到失败页面 21 * @author qjj 22 * 23 */ 24 public class LoginServlet extends HttpServlet { 25 26 private static final long serialVersionUID = 1L; 27 28 @Override 29 protected void doPost(HttpServletRequest request, HttpServletResponse response) 30 throws ServletException, IOException { 31 //设置字符编码方式 32 request.setCharacterEncoding("UTF-8"); 33 //获取用户名和密码 34 String username = request.getParameter("username"); 35 String password = request.getParameter("password"); 36 //连接数据库验证用户名和密码 37 Connection conn = null; 38 PreparedStatement ps = null; 39 ResultSet rs = null; 40 boolean loginSuccess = false; 41 String realName = null; 42 try{ 43 Class.forName("com.mysql.jdbc.Driver"); 44 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "root", "248xiaohai"); 45 String sql = "select id,username,password,realname from t_user where username=? and password=?"; 46 ps = conn.prepareStatement(sql); 47 ps.setString(1, username); 48 ps.setString(2, password); 49 rs = ps.executeQuery(); 50 if(rs.next()){ 51 loginSuccess = true; 52 realName = rs.getString("realname"); 53 } 54 } catch (Exception e) { 55 e.printStackTrace(); 56 } finally { 57 if(rs != null){ 58 try { 59 rs.close(); 60 } catch (SQLException e) { 61 e.printStackTrace(); 62 } 63 } 64 if(ps != null){ 65 try { 66 ps.close(); 67 } catch (SQLException e) { 68 e.printStackTrace(); 69 } 70 } 71 if(conn != null){ 72 try { 73 conn.close(); 74 } catch (SQLException e) { 75 e.printStackTrace(); 76 } 77 } 78 } 79 //登录成功跳转到成功页面,失败跳转到失败页面 80 if(loginSuccess){ 81 //登陆成功之后,获取用户是否选择了十天内免登陆 82 String tenDayAutoLoginFlag = request.getParameter("tenDayAutoLoginFlag"); 83 if("ok".equals(tenDayAutoLoginFlag)){ 84 //创建Cookie对象 85 Cookie cookie1 = new Cookie("username",username); 86 Cookie cookie2 = new Cookie("password",password); 87 //设置有效时间 88 cookie1.setMaxAge(60 * 60 * 24 * 10); 89 cookie2.setMaxAge(60 * 60 * 24 * 10); 90 //设置关联路径 91 cookie1.setPath(request.getContextPath()); 92 cookie2.setPath(request.getContextPath()); 93 //发送Cookie给浏览器 94 response.addCookie(cookie1); 95 response.addCookie(cookie2); 96 } 97 98 response.setContentType("text/html;charset=UTF-8"); 99 PrintWriter out = response.getWriter(); 100 out.print("<html>"); 101 out.print("<head>"); 102 out.print("<title>欢迎页面</title>"); 103 out.print("</head>"); 104 out.print("<body>"); 105 out.print("欢迎"); 106 out.print(realName); 107 out.print("访问"); 108 out.print("</body>"); 109 out.print("</html>"); 110 }else{ 111 response.sendRedirect(request.getContextPath() + "/login_error.html"); 112 } 113 } 114 }
前端HTML:
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> 2 <html> 3 <head> 4 <title>登录页面</title> 5 6 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 7 <meta http-equiv="description" content="this is my page"> 8 <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 9 10 <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 11 12 </head> 13 14 <body> 15 16 <form action="/prj-servlet-20/login" method="post"> 17 用户名 18 <input type="text" name="username"> 19 <br> 20 密码 21 <input type="password" name="password"> 22 <br> 23 <input type="checkbox" name="tenDayAutoLoginFlag" value="ok">十天内免登陆<br> 24 <input type="submit" value="登录"> 25 </form> 26 27 </body> 28 </html>
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> 2 <html> 3 <head> 4 <title>登录失败</title> 5 6 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 7 <meta http-equiv="description" content="this is my page"> 8 <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 9 10 <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 11 12 </head> 13 14 <body> 15 16 登录失败,用户名不存在或者密码错误,请<a href="/prj-servlet-20/login.html">重新登录</a> 17 18 </body> 19 </html>
web.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 6 id="WebApp_ID" version="2.5"> 7 <!-- 设置isLogin为欢迎页面 --> 8 <welcome-file-list> 9 <welcome-file>isLogin</welcome-file> 10 </welcome-file-list> 11 12 <servlet> 13 <servlet-name>login</servlet-name> 14 <servlet-class>com.bjpowernode.javaweb.servlet.LoginServlet</servlet-class> 15 </servlet> 16 <servlet-mapping> 17 <servlet-name>login</servlet-name> 18 <url-pattern>/login</url-pattern> 19 </servlet-mapping> 20 21 <servlet> 22 <servlet-name>isLogin</servlet-name> 23 <servlet-class>com.bjpowernode.javaweb.servlet.CheckLoginStatusServlet</servlet-class> 24 </servlet> 25 <servlet-mapping> 26 <servlet-name>isLogin</servlet-name> 27 <url-pattern>/isLogin</url-pattern> 28 </servlet-mapping> 29 </web-app>