Session 可以理解为一种机制。如果没有 session ,其实每次用户从浏览器向服务器发送一个 http 请求,接收返回请求后,客户端和服务器端就没有联系了,即 Server 就不认识该 Client 了,就无法记录和跟踪 Client 的动作。
Session 运行机制:
1. 当一个 Client 首次访问 Server 时, Server 会给 Client 创建一个 HttpSession 对象,该对象存放着 Client 的相关信息。
2. Server 会给该对象分配一个 Session ID ,客户端浏览器将该 Session ID 作为 cookie 保存在浏览器中。
3. 当该用户再次访问服务器端时,服务器端可以从 HttpRequest 对象中取得 Session ID, 根据 Session ID 就可以找到对应的 HttpSession 了,从中取出所需的信息。
Session 的生命周期:
Session 是有生命周期的,我们可以访问服务器端时, session 诞生,以下有三种 session 死亡的途径:
1 .客户端关闭浏览器
2 . Session 过期了
3 .服务器调用了 invalidate ()
以下为session的示例代码:
- import java.io.IOException;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- /**
- * Servlet implementation class MyServlet
- */
- public class MyServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * @see HttpServlet#HttpServlet()
- */
- public MyServlet() {
- super ();
- // TODO Auto-generated constructor stub
- }
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- response.setContentType("text/html;charset=gbk" );
- // out.println("你登陆成功了!");
- String initName=this .getInitParameter( "userName" );
- String initPWD=this .getInitParameter( "pwd" );
- String name=request.getParameter("userName" );
- String pwd=request.getParameter("pwd" );
- if (initName.equalsIgnoreCase(name)&&initPWD.equalsIgnoreCase(pwd))
- {
- HttpSession session=request.getSession(true );
- session.setAttribute("loginState" , "OK" );
- session.setAttribute("useraName" , name);
- request.getRequestDispatcher("LoginOK.html" ).forward(request, response);
- }
- }
- }