Session

Session
每一个连接到服务器的客户端都是session
servlet用此接口创建客户端服务器之间的会话
是存在服务端的
优点:安全性高
缺点:session 是保存在服务端的,每个用户都会产生一个session,并发访问多的话,每个用户都会生成session,消耗内存

@WebServlet("/ss1")
public class Session1 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取session 先判断是否存在 不存在则创建
        HttpSession sess=req.getSession();

        //获取session的会话标识符
        String id=sess.getId();
        System.out.println(id);

            //获取创建时间
            System.out.println(sess.getCreationTime());

            //获取最后一次时间
            System.out.println(sess.getLastAccessedTime());

            //判断是否是新的session对象
            System.out.println(sess.isNew());

        //设置域对象
        sess.setAttribute("sess","sexx");
        sess.setAttribute("sess1","sexx");
        //移除域对象
        sess.removeAttribute("sess");

        //请求转发
        req.getRequestDispatcher("index.jsp").forward(req,resp);
        //重定向
        resp.sendRedirect("index.jsp");

        /**
         * session对象销毁
         *      1.到期时间
         *         tomcat 默认30分钟失效 不操作页面的时间
         *         自定义
         *      2.立即销毁
         *      3.关闭浏览器立即失效
         */
        //最大不活动时间
        sess.getMaxInactiveInterval();
        //15秒
        sess.setMaxInactiveInterval(15);
        //立即销毁
        sess.invalidate();
    }
}
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <%
    //获取Session对象
    String sess0=(String) request.getSession().getAttribute("sess");
    String sess1=(String) request.getSession().getAttribute("sess1");
    System.out.println(sess0+" "+sess1);

    //获取request参数
    String uname=request.getParameter("uname");
    String pwd=(String) request.getAttribute("pwd");
    System.out.println(uname+" "+pwd);
  %>
  </body>
</html>
posted @ 2022-04-13 18:56  lwx_R  阅读(28)  评论(0编辑  收藏  举报