session

public class SessionDemo1 extends HttpServlet {
11 
12     public void doGet(HttpServletRequest request, HttpServletResponse response)
13             throws ServletException, IOException {
14 
15         response.setCharacterEncoding("UTF=8");
16         response.setContentType("text/html;charset=UTF-8");
17         //使用request对象的getSession()获取session,如果session不存在则创建一个
18         HttpSession session = request.getSession();
19         //将数据存储到session中
20         session.setAttribute("data", "孤傲苍狼");
21         //获取session的Id
22         String sessionId = session.getId();
23         //判断session是不是新创建的
24         if (session.isNew()) {
25             response.getWriter().print("session创建成功,session的id是:"+sessionId);
26         }else {
27             response.getWriter().print("服务器已经存在该session了,session的id是:"+sessionId);
28         }
29     }
用isNew()方法来判断Session是不是新创建的。

浏览器禁用Cookie后的session处理
解决方案:URL重写
  response.encodeRedirectURL(java.lang.String url)用于对sendRedirect方法后URL地址进行重写
  response.encodeURL(java.lang.String url)用于对表单action和超链接的URL地址进行重写。
session的销毁:
  在web.xml中
    <!-- 设置Session的有效时间:以分钟为单位-->
      <session-config>
        <session-timeout>15</session-timeout>
      </session-config>

在程序中手动设置session失效。
  1 HttpSession session = request.getSession();
  2 //手工调用session.invalidate方法,摧毁session
   3 session.invalidate();


原文地址:https://www.cnblogs.com/bulrush/p/5668579.html