image.png
    HttpSession对象的创建是通过request.getSession()方法来创建的。客户端浏览器在请求服务端资源时,如果在请求中没有jsessionid,getSession()方法将会为这个客户端浏览器创建一个新的HttpSession对象,并为这个HttpSession对象生成一个jsessionid,在响应中通过状态Cookie写回给客户端浏览器,如果在请求中包含了jsessionid,getSession()方法则根据这个ID返回与这个客户端浏览器对应的HttpSession对象。
    getSession()方法还有一个重载方法getSession(true|false)。当参数为true时与getSession()方法作用相同。当参数为false时则只去根据jsessionid查找是否有与这个客户端浏览器对应的HttpSession,如果有则返回,如果没有jsessionid则不会创建新的HttpSession对象。

    1. import javax.servlet.ServletException;
    2. import javax.servlet.http.HttpServlet;
    3. import javax.servlet.http.HttpServletRequest;
    4. import javax.servlet.http.HttpServletResponse;
    5. import javax.servlet.http.HttpSession;
    6. import java.io.IOException;
    7. import java.io.PrintWriter;
    8. public class CreatHttpSessionServlet extends HttpServlet {
    9. @Override
    10. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    11. this.doPost(req, resp);
    12. }
    13. @Override
    14. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    15. //创建httpsession对象
    16. HttpSession httpSession =req.getSession();
    17. System.out.println(httpSession);
    18. PrintWriter printWriter = resp.getWriter();
    19. printWriter.println("创建Session成功");
    20. printWriter.flush();
    21. printWriter.close();
    22. }
    23. }