SessionServlet.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.lovecoding.request;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.annotation.WebServlet;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import javax.servlet.http.HttpSession;
  8. import java.io.IOException;
  9. @WebServlet("/session")
  10. public class SessionServlet extends HttpServlet{
  11. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  12. req.setCharacterEncoding("UTF-8");
  13. /**
  14. * 最初 WAP 年代, 用户身份ID 是URL 里保存携带的
  15. * 后来 就开始使用 Session , 主要是用浏览器 cookie 存储用户身份ID
  16. * 再后来 就开始使用 浏览器 session 存储用户身份ID
  17. * 现在呢 我们使用 JWT 技术, 把用户的数据信息 加密存储到 浏览器端, 通过Header 传递到服务器
  18. */
  19. //获取用户Session, 参数的意思是 如果没有给用户开启Session 则开启session
  20. HttpSession session = req.getSession(true);
  21. System.out.println( session.getId() );
  22. String username = req.getParameter("username");
  23. if ( username == null ) {
  24. username = "";
  25. }
  26. session.setAttribute("name", username );
  27. Brand brand = new Brand();
  28. brand.setBrandName("新华书社");
  29. brand.setCompanyName("新华");
  30. brand.setDescription("新华出版社");
  31. brand.setId(1);
  32. /**
  33. * 也即是说 Session 是持久化的, session没过期之前都可以读取数据
  34. * Request 是临时的, 数据是在内存里传递的
  35. */
  36. session.setAttribute( "brand", brand );
  37. req.setAttribute( "brand", brand );
  38. req.getRequestDispatcher("./session.jsp").forward(req, resp);
  39. }
  40. }