Session域
有效范围
单次会话内有效,可以跨多个请求
生命周期
创建 会话的产生,第一次发生请求,会话的开始
使用 本次会话之内,浏览器和服务器之间发生多次请求和响应有效
销毁 会话结束,如:浏览器失去JSESSIONID、到达最大不活动时间、手动清除
测试代码
Session域中放入数据
package com.msb.testSession;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;import java.io.IOException;import java.util.ArrayList;import java.util.Collections;import java.util.List;/** * @Author: Ma HaiYang * @Description: MircoMessage:Mark_7001 */@WebServlet(urlPatterns = "/addToSession.do")public class Servlet1 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 向Session域中添加数据 HttpSession session = req.getSession(); List<String> x=new ArrayList<>(); Collections.addAll(x, "a","b","c"); session.setAttribute("list", x); session.setAttribute("gender","boy"); session.setAttribute("gender","girl"); session.setAttribute("name","晓明"); // 重定向 resp.sendRedirect("readFromSession.do"); }}
从Session域中读取数据
package com.msb.testSession;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;import java.io.IOException;import java.util.List;/** * @Author: Ma HaiYang * @Description: MircoMessage:Mark_7001 */@WebServlet(urlPatterns="/readFromSession.do")public class Servlet2 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); // 移除域中的互数据 //session.removeAttribute("gender"); // 从request域中读取数据 List<String> list =(List<String>) session.getAttribute("list"); System.out.println(list); System.out.println(session.getAttribute("gender")); System.out.println(session.getAttribute("name")); //获取Request中的请求参数 System.out.println(req.getParameter("username")); System.out.println(req.getParameter("password")); }}