1. 自动登录 的需求
① 不需要填写用户名和密码等信息,可以自动登录到系统
② login.jsp hello.jsp
login.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 11 12 <form action="index.jsp"> 13 name:<input type="text" name="name"/> 14 <input type="submit" value="submit"/> 15 16 17 </form> 18 19 </body> 20 </html>
hello.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>自动登陆测试</title> 8 </head> 9 <body> 10 11 <% 12 //1.若可以获取到请求参数 name, 则打印出欢迎信息。把登录信息存储到 Cookie 中,并设置 Cookie 的最大时效为 30S 13 String name = request.getParameter("name"); 14 if(name != null && !name.trim().equals("")){ 15 16 //创建并且发送cookie 17 Cookie cookie = new Cookie("loginName",name); 18 cookie.setMaxAge(30); 19 response.addCookie(cookie); 20 }else{ 21 //2.从 Cookie 中读取用户信息,若存在则打印欢迎信息 22 Cookie[] cookies = request.getCookies(); 23 if(cookies != null && cookies.length > 0){ 24 for(Cookie cookie : cookies){ 25 String cookieName = cookie.getName(); 26 if("loginName".equals(cookieName)){ 27 String value = cookie.getValue(); 28 name = value; 29 30 } 31 } 32 } 33 34 35 } 36 if(name != null && !name.trim().equals("")){ 37 out.print("欢迎登陆" + name); 38 }else{ 39 //3.若既没有请求参数,也没有 Cookie,则重定向到 login.jsp 40 request.getRequestDispatcher("/app-1/login.jsp"); 41 } 42 43 44 45 46 47 %> 48 </body> 49 </html>