JavaWeb学习笔记-使用HttpSession对象跟踪会话
使用HttpSession接口开发的步骤:
1.获取HttpSession对象
2.对HttpSession对象进行读写
3.手工终止HttpSession,或者自动终止
常用方法:
getId():返回包含分配给这个会话的唯一表示的字符串。在使用URL改写以及标识会话时比较有用
setAttribute():使用指定的名称将对象绑定到这个会话。(setValue()方法)
getAttribution():返回绑定到此会话的对象。(getValue()方法)
invalide():终止当前会话
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取会话对象 HttpSession session = request.getSession(true); response.setContentType("text/html;charset=GB2312"); response.setCharacterEncoding("gb2312");//确保参数信息以汉字编码方式提取 PrintWriter out = response.getWriter(); //从会话中获取属性 int count =1; Integer i = (Integer)session.getAttribute(COUNTER_KEY); //如果存在以前的数值 if(i!=null){ count=i.intValue()+1; } //将属性信息存入会话 session.setAttribute(COUNTER_KEY, new Integer(count)); Date lastAccessed = new Date(session.getLastAccessedTime()); Date sessionCreated = new Date(session.getCreationTime()); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM); //输出对话信息 out.println("<html>"); out.println("<head>"); out.println("<title>会话计数器</title>"); out.println("</head>"); out.println("<body>"); out.println("你的会话ID:<b>"+session.getId()+"<br>"); out.println("会话创建时间:"+formatter.format(sessionCreated)+"<br>"); out.println("会话上次访问时间:"+formatter.format(lastAccessed)+"<br>"); out.println("</b>会话期间你向页面发起<b>"+count+"</b>次请求"); out.println("<form method=GET action=\""+request.getRequestURI()+"\">"); out.println("<input type='submit'"+"value=\"再次点击...\">"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request,response); }