利用Cookie和Session保持WEB客户端始终在线

来源:互联网 发布:淘宝阿里旅行人工电话 编辑:程序博客网 时间:2024/03/28 21:57

声明:引用本文时请注明出处。

 

问题描述:有些WEB业务系统,比如物流、ERP等用户比较习惯把浏览器一直打开,当有新业务发生时,用户会即时录入,当通过SESSION时,由于会话已过期,经常会导致提交失败,用户不得不又要重新登陆并录入单据,影响系统的使用。

 

分析:做WEB开发的用户基本都会遇到保持用户会话的问题,由于HTTP协议是一个无状态的协议,所以我们不得不利用Cookie(客户端方式)或利用SESSION(服务器方式,新打开的浏览器时会自动创建一个SESSIONID,名称随应用服务器而不同),用Cookie时不安全,因为它是附在HTTP请求的头信息里的,在浏览器地址栏中输入“javascript:document.write(document.cookie)”可显示COOKIE信息(IE6和IE7中均可以),Session又受服务器限制,一般会限制十几至几十分钟以内。下面介绍一种折衷的办法,利用Cookie与Session相结合的办法,保持服务器一直在线。

 

解决办法:(JAVA代码)

1,用户登陆时,在保存SESSION信息同时,将登陆信息以加密的方式保存到Cookie中。

   //以下为代码片段,拷贝后需要处理

public static String checkAuth(HttpServletRequest request,HttpServletResponse response,String mark,String userid,String pwd){
  UserAuthClient userAuth= new UserAuthClient();
  String info=userAuth.getUserAuthHttpPort().check(userid,pwd,request.getRemoteAddr());
  if(info.equals("ok")){
   HttpSession session=request.getSession();
   DESPlus des;
   try {
    des = DESPlus(request.getRemoteAddr());//加密密码为IP地址
    setCookie(request,response,"SN",des.encrypt(userid+";"+pwd));//设置Cookie

    session.setAttribute("Employee", employee);//设置SESSION
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return info;
  
 }

 

 

2,验证用户

//查看用户存根是否存在,如果存在通过用户存根直接通过存根创建用户登陆信息

public static Employee getEmployee(HttpServletRequest request,HttpServletResponse response){
  //用户是否已经登陆,如果已经登陆,则返回用户信息

  HttpSession session=request.getSession();
  Employee employee=(Employee)session.getAttribute("Employee");
  if(employee!=null)return employee;//验证成功


  DESPlus des;
  try {
   des = new DESPlus(request.getRemoteAddr());
   String SN=getCookiebyName(request,"SN");
   if(SN==null)return null;
   SN=des.decrypt(SN);
   if(SN==null)return null;
   String [] strs=SN.split(";");
   if(strs==null || strs.length!=2)return null;

   String userid=str[0];

   String pwd=str[1];
   String isok=checkAuth(request,response,userid,pwd);//重新登陆,成功时会创建会话
   if(isok.equals("ok")){
    return (Employee)session.getAttribute("Employee");
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return employee;

 }


  

原创粉丝点击