session的应用

session存储数据用的方法时

session.setAttribute("",)存储一个键值对

 

@WebServlet("/session")
public class sessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过request获取session
        HttpSession session = req.getSession();
        session.setAttribute("username","gavin");
        System.out.println(session.getId());
    }
@WebServlet("/getsession")
public class Getsession extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //首先,因为之前是在session类中拿的session,和getsession并无关系,所以还要获取session
        HttpSession session = req.getSession();
        //获得session中的值
        String s = (String) session.getAttribute("username");
        System.out.println("获得的username是"+s);

    }

 session的生命周期

 

session.setMaxinactiveInterval()设置有效时间

session.invalidate()手工销毁

当浏览器禁用cookie时可以写

 

 

对重定向的路径进行一个重写,用于解决cookie被禁用

 

posted @ 2022-04-26 10:42  软工小蜗牛  阅读(105)  评论(0编辑  收藏  举报