原理:
下面一个简单的demo:在访问购买servlet时创建一个session,key为name
在访问购买servlet时取出值来进行购买
/** * 购买servlet */ @WebServlet("/sessionDemo1") public class sessionDemo1 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); session.setAttribute("name", "洗衣机"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
/** * 结账servlet */ @WebServlet("/sessionDemo2") public class sessionDemo2 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF_8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); Object value=request.getSession().getAttribute("name"); out.write(value.toString()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
session生命周期:
第一个getsession出现时创建,第二getssesion出现时取值
默认30分钟没活动就会才摧毁
也可以设失效时间在web.xml
------>十分钟失效
代码方式摧毁session
session.invalidate();
场景————————》电商网站,选择好的商品关闭浏览器就丢失,所以这里需要分析下session的原理
每个浏览器有一个session,两个连接的关键点在于用JSESSIONID来寻找对应的session
关闭浏览器,再重新访问,虽然session还存在,因为JSESSIONID没有传入进来所以不知道寻找哪个session
通过如下代码给浏览器回写给浏览器JSESSIONID:
HttpSession session=request.getSession(); String sessionId=session.getId(); Cookie cookie=new Cookie("JSESSIONID", sessionId); cookie.setMaxAge(30*60); cookie.setPath("/day06"); response.addCookie(cookie);
浏览器可以控制cookie被禁,因为session基于cookies,这样session也就不能正常进行
getsession这个方法逻辑是这样的------》先判断是否以cookies回写JSESSION,在判断是否以URL形式带来JSESSION,都没有创建新的session
如果这样写----》getsession(false)只读取,不创建
所以解决cookie被禁的方法是重写url
response.encodeURL(URL)----->自动给这个url加上JSESSION
特例:在IE8版本的浏览器里,开新浏览器不创建新的session,用的是同一个
下面给一个用户登录时,密码正确就给用户一个登录的session标记,退出就销毁session,下面是demo
效果:
先登录----》aa aa---->登录成功------》注销----》弹回登录页面
-----》----
---》-----》
LoginServlet.java
/** * 登录 */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF_8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); String username=request.getParameter("username"); String password=request.getParameter("password"); List<User> lists=DB.getAll(); for(User list:lists){ if(list.getUsername().equals(username)){ if(list.getPassword().equals(password)){ request.getSession().setAttribute("user", list);// 登录成功往session里存入登录标记 response.sendRedirect("/day06/index.jsp");//重定向到首页 return; } } } out.write("用户名或者密码不对"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } @SuppressWarnings("unchecked") class DB{//模拟数据库 @SuppressWarnings("rawtypes") public static List list=new ArrayList(); static{ list.add(new User("aa","aa")); list.add(new User("bb","bb")); list.add(new User("cc","cc")); } @SuppressWarnings("rawtypes") public static List getAll(){ return list; } }
login.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="/day06/LoginServlet" method="post "> 用户名:<input type="text" name="username" /> 密码:<input type="password" name="password" /> <input type="submit" value="提交"> </form> </body> </html>
user.java(用户实体)
/** * */ package session; /** * @author: snowing * @date : 2017年4月9日 * */ public class User { private String username; private String password; /** * @param string * @param string2 */ public String getUsername() { return username; } public User() { super(); // TODO Auto-generated constructor stub } public User(String username, String password) { super(); this.username = username; this.password = password; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
index.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> success!!${user.username} <a href="/day06/LoginoutServlet">注销登录</a> </body> </html>
LoginoutServlet.java
/** * 登出 */ @WebServlet("/LoginoutServlet") public class LoginoutServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(false); if(session==null){ response.sendRedirect("/day06/login.html"); return; } session.removeAttribute("user"); response.sendRedirect("/day06/login.html"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }