HttpSession
HttpSession 服务端技术
HttpSession原理
当用户端第一次访问Servlet时 服务端会给该用户创建
一个独立Session 并且生成一个SessionID
这个SessionID在响应浏览器的时候 会被装进cookie中
从而被保存到浏览器中
当用户再一次访问 Servlet的时候
请求中会携带着 cookie中的 SessionID 去访问
服务器会根据这个SessionID 去查看是否有对应的 Session对象
有 就拿出来用
没有 就创建一个Session(相当于第一次访问)
Session域 只要会话不结束 就会存在
但是 Session有默认的存活时间 30分钟
以下面两个demo为例 具体看一下Session对象的作用
public class Demo01 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
HttpSession session = request.getSession();
session.setAttribute("username", username);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
public class Demo02 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
String username = (String)session.getAttribute("username");
response.getWriter().write(username + " " + session.getId());
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}