Servlet中的Session使用方法
Servlet中的doGet方法:
1 protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { 2 request.setCharacterEncoding("utf-8"); 3 response.setContentType("text/html;charset=utf-8"); 4 // 调用 HttpServletRequest 的公共方法 getSession() 来获取 HttpSession 对象,如果没有,则创建一个 5 HttpSession session = request.getSession(); 6 // 返回session对象中与指定名称绑定的对象,如果不存在则返回null(记得将返回后的Object类型转换为对象原本的类型) 7 Integer accessedCount = (Integer)session.getAttribute("accessedCount"); 8 if (accessedCount == null) { 9 accessedCount = new Integer(0); 10 session.setAttribute("accessedCount", accessedCount); 11 } 12 13 PrintWriter out = response.getWriter(); 14 out.print("创建session成功"); 15 }
使用Servlet中的request对象获取session对象并输出其属性:
1 HttpSession session = request.getSession(); 2 Integer accessedCount = (Integer)session.getAttribute("accessedCount"); 3 if (accessedCount == null) { 4 accessedCount = new Integer(0); 5 } else { 6 accessedCount = new Integer(accessedCount.intValue()+1); 7 } 8 // 每次更新对象的值都需要重新设置session中的属性 9 session.setAttribute("accessedCount", accessedCount); 10 11 PrintWriter out = response.getWriter(); 12 out.print("sessionId: " + session.getId() + "<br />"); 13 out.print("sessionCreationTime: " + new Date(session.getCreationTime()) + "<br />"); 14 out.print("sessionLastAccessedTime: " + new Date(session.getLastAccessedTime()) + "<br />"); 15 out.print("被访问的次数: " + session.getAttribute("accessedCount") + "<br />");
遇到的疑惑(已解决):
1、Integer对象并不能直接改变值,只能新分配一个对象。