Session技术是指使用HttpSession对象实现会话跟踪的技术,是一种在服务器端保持会话跟踪的解决方案。HttpSession对象也被称为会话对象,该对象用来保存单个用户访问时的一些信息,是服务器在无状态的http协议下用来识别和维护具体某个用户的主要方式
HttpSession对象会在用户第一次访问服务器时由容器创建(只有访问jsp,servlet等才会创建),当用户调用其失效方法(incalidate()方法)或超过其最大不活动时间时会失效。在此之间,用户与服务器之间的多次请求都属于同一个会话。
服务器在创建会话对象时,会为其分配一个唯一的会话标识,SessionID,以“JSESSIONID”的属性名保存在客户端Cookie中,在用户随后的请求中,服务器会读取Cookie中的JSESSIONID属性值来标识不同的用户,从而实现对每个用户的会话跟踪
HttpServletRequest接口提供了获取HttpSession对象的方法:
方法 | 描述 |
getSession() | 获取与客户端请求关联的当前的有效的Session,若没有则新建一个 |
getSession(boolean create) | 获取与客户端请求关联的当前的有效的Session,若参数为真,则新建一个,若参数为假,则返回空值 |
HttpSession接口提供了存取会话域属性和管理会话生命周期的方法:
方法 | 描述 |
void setAttribute(String key, Object value) | 以key/value形式将对象保存在HttpSession对象中 |
Object getAttribute(String key) | 通过key获取值 |
void removeAttribute(String key) | 通过key删除session中对应的对象 |
void invalidate() | 设置HttpSession对象失效 |
void setMaxInactiveInterval(int interval) | 设置HttpSession对象非活动时间,若超过这个时间,则HttpSession失效 |
int getMaxInactiveInterval() | 获取HttpSession对象非活动时间(以秒为单位) |
String getId() | 获取HttpSession对象的表示sessionid |
long getCreationTime() | 获取HttpSession对象的产生的时间(以毫秒为单位) |
long getLastAccessedTime() | 获取用户最后通过这个HttpSession对象送去请求的时间 |
也可以通过在web.xml中配置会话最大不活动时间:
<session-config> <session-timeout>10</session-timeout> </session-config>
利用Session实现购物车:
buybook.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> <form action="./SessionTest1" method = "post"> <input type = "checkbox" name = "book" value = "语文">语文<br/> <input type = "checkbox" name = "book" value = "数学">数学<br/> <input type = "checkbox" name = "book" value = "英语">英语<br/> <input type = "submit" value = "提交"/> </form> </body> </html>
SessionTest1.java
package com.servlet; import java.io.IOException; import java.util.*; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/SessionTest1") public class SessionTest1 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //将页面接受到的数据进行编码 request.setCharacterEncoding("utf-8"); //获取session HttpSession session = request.getSession(); //获取car Map<String,Integer> car = (Map<String,Integer>)session.getAttribute("car"); //如果car为空,则创建一个car if(car==null) { car = new HashMap<String,Integer>(); } //获取用户选择的书籍 String[] books = request.getParameterValues("book"); //判断是否选择过,并进行相应处理 if(books != null && books.length > 0) for (String book : books) { if(car.get(book)!=null) { int num = car.get(book); car.put(book, num+1); } else { car.put(book, 1); } } //设置car session.setAttribute("car", car); //重定向到显示页面 response.sendRedirect(request.getContextPath()+"/SessionTest2"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
SessionTest2.java
package com.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; @WebServlet("/SessionTest2") public class SessionTest2 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); //通过session获取到数据 Map<String,Integer> car = (Map<String,Integer>)request.getSession().getAttribute("car"); //输出数据 if(car !=null && car.size()>0) { out.println("您购买的书籍有:<br/>"); for (String book : car.keySet()) { out.print(book + ", 数量:" + car.get(book)+"<br/>"); } } //返回购买页面 out.print("<a href='buybook.jsp'>继续购买</a>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }