Session机制(是对cookie的作用的提升,使用较多)
1.Session作用类似于购物车,第一次,放入物品,可以获得Session的id,并可以设置id失效的时间,这样便于多次将物品放在购物车里面,使用的就是获取的Session的id;
2.Session的常用方法:sessionid,获取首次访问的id值,及在jsp页面直接的跳转,这个是login.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> SessionID: <%= session.getId() %> <br><br> IsNew: <%= session.isNew() %> <br><br> MaxInactiveInterval: <%= session.getMaxInactiveInterval() %> <br><br> CreateTime: <%= session.getCreationTime() %> <br><br> LastAccessTime: <%= session.getLastAccessedTime() %> <br><br> <% Object username = session.getAttribute("username"); if(username == null){ username = ""; } %> <form action="<%= response.encodeURL("hello.jsp") %>" method="post"> username: <input type="text" name="username" value="<%= username %>"/> <input type="submit" value="Submit"/> </form> </body> </html>
3.hello.jsp页面,有注销和重新登陆的功能,点击注销跳转到logout.jsp页面,有实现注销session的方法,点击重新登陆返回到login页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> SessionID: <%= session.getId() %> <br><br> IsNew: <%= session.isNew() %> <br><br> MaxInactiveInterval: <%= session.getMaxInactiveInterval() %> <br><br> CreateTime: <%= session.getCreationTime() %> <br><br> LastAccessTime: <%= session.getLastAccessedTime() %> <br><br> Hello: <%= request.getParameter("username") %> <br><br> <% session.setAttribute("username", request.getParameter("username")); %> <a href="<%= response.encodeURL("login.jsp") %>">重新登录</a> <a href="<%= response.encodeURL("logout.jsp") %>">注销</a> </body> </html>
4.logout.jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> SessionID: <%= session.getId() %> <br><br> IsNew: <%= session.isNew() %> <br><br> MaxInactiveInterval: <%= session.getMaxInactiveInterval() %> <br><br> CreateTime: <%= session.getCreationTime() %> <br><br> LastAccessTime: <%= session.getLastAccessedTime() %> <br><br> Bye: <%= session.getAttribute("username") %> <br><br> <a href="login.jsp">重新登录</a> <% session.invalidate(); %> </body> </html>