Session解析

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的示例代码:

Java代码
  1. import  java.io.IOException;  
  2. import  java.io.PrintWriter;  
  3.   
  4. import  javax.servlet.ServletException;  
  5. import  javax.servlet.http.HttpServlet;  
  6. import  javax.servlet.http.HttpServletRequest;  
  7. import  javax.servlet.http.HttpServletResponse;  
  8. import  javax.servlet.http.HttpSession;  
  9.   
  10. /**  
  11.  * Servlet implementation class MyServlet  
  12.  */   
  13. public   class  MyServlet  extends  HttpServlet {  
  14.     private   static   final   long  serialVersionUID = 1L;  
  15.          
  16.     /**  
  17.      * @see HttpServlet#HttpServlet()  
  18.      */   
  19.     public  MyServlet() {  
  20.         super ();  
  21.         // TODO Auto-generated constructor stub   
  22.     }  
  23.   
  24.     /**  
  25.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)  
  26.      */   
  27.     protected   void  service(HttpServletRequest request, HttpServletResponse response)  throws  ServletException, IOException {  
  28.         // TODO Auto-generated method stub   
  29.         response.setContentType("text/html;charset=gbk" );  
  30.           
  31.     //  out.println("你登陆成功了!");   
  32.         String initName=this .getInitParameter( "userName" );  
  33.         String initPWD=this .getInitParameter( "pwd" );  
  34.           
  35.         String name=request.getParameter("userName" );  
  36.         String pwd=request.getParameter("pwd" );  
  37.         if (initName.equalsIgnoreCase(name)&&initPWD.equalsIgnoreCase(pwd))  
  38.         {  
  39.             HttpSession session=request.getSession(true );  
  40.             session.setAttribute("loginState""OK" );  
  41.             session.setAttribute("useraName" , name);  
  42.             request.getRequestDispatcher("LoginOK.html" ).forward(request, response);  
  43.         }  
  44.       
  45.     }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值