12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- package com.lovecoding.request;
- 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;
- @WebServlet("/session")
- public class SessionServlet extends HttpServlet{
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("UTF-8");
- /**
- * 最初 WAP 年代, 用户身份ID 是URL 里保存携带的
- * 后来 就开始使用 Session , 主要是用浏览器 cookie 存储用户身份ID
- * 再后来 就开始使用 浏览器 session 存储用户身份ID
- * 现在呢 我们使用 JWT 技术, 把用户的数据信息 加密存储到 浏览器端, 通过Header 传递到服务器
- */
- //获取用户Session, 参数的意思是 如果没有给用户开启Session 则开启session
- HttpSession session = req.getSession(true);
- System.out.println( session.getId() );
- String username = req.getParameter("username");
- if ( username == null ) {
- username = "";
- }
- session.setAttribute("name", username );
- Brand brand = new Brand();
- brand.setBrandName("新华书社");
- brand.setCompanyName("新华");
- brand.setDescription("新华出版社");
- brand.setId(1);
- /**
- * 也即是说 Session 是持久化的, session没过期之前都可以读取数据
- * Request 是临时的, 数据是在内存里传递的
- */
- session.setAttribute( "brand", brand );
- req.setAttribute( "brand", brand );
- req.getRequestDispatcher("./session.jsp").forward(req, resp);
- }
- }
|