维护当前用户和Web应用的状态通过以下两种方式实现:
一种是通过Cookie方式实现,一种是通过Session方式实现。
Cookie通过在客户端保存用户的信息,每次服务器端回去读取客户端的Cookie中的信息。
Session通过两种方式实现:
一种是把一个名为JSESSIONID的十六进制数字的信息保存到Cookie中标识每一个访问的用户。
一种是通过URL重写的方式就是把每个用户的jsessionid的值附加到URL中,实现会话功能。
HttpSessionTest
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class HttpSessionTest extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Integer count = (Integer) session.getAttribute("counter"); if (count == null) { count = 1; } else { count++; } session.setAttribute("counter", new Integer(count)); request.getRequestDispatcher("/count.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
count.jsp
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK" session="true"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>访问量统计</title> </head> <body> <% HttpSession httpSession = request.getSession(); Integer count = (Integer)httpSession.getAttribute("counter"); out.println("当前访问量为:"+count); %> </body> </html>