Cookie的存入和读取,并解决中文问题

1.当一个登录成功以后

CookieProcess co=new CookieProcess();

String PerID = Rs.getString("ID");
      String PerName = Rs.getString("Name");
      session.setAttribute("PerID", perID);
      session.setAttribute("PerName",PerName);
      co.add(response,"PerID",PerID);
      co.add(response,"PerName", java.net.URLEncoder.encode(PerName));

//在这里我们存用户名的时候采用java.net.URLEncoder.encode(PerName)的方式存到COOKIE中去。

取的时候采用returnStr= java.net.URLDecoder.decode(cookie_get[i].getValue().toString());的方式取数据

将用户名和密码都存入到session和cookie中

2.然后取数据的时候

我们将用户名和密码都放入到form中,首先从SESSION中取,如果取得的值为空,然后我们再从COOKIE中取

BeanForm infoform = new BeanForm();

infoform.setOperID(StrUtil.nullToEmpty(String.valueOf(session.getAttribute("PerID"))));
    infoform.setOperName(StrUtil.nullToEmpty(String.valueOf(session.getAttribute("PerName"))));
   
    if("".equals(infoform.getOperID())||infoform.getOperID()==null||"".equals(infoform.getOperName())||infoform.getOperName()==null)
    {
     infoform.setOperID(co.get(request,"PerID"));
     infoform.setOperName(co.get(request,"PerName"));
    }

3.CookieProcess代码

package subsystem.talent.trainacquaintance;

import javax.servlet.http.*;

public class CookieProcess
{
 Cookie[] cookie_get={};
 
 //Add 方法,向客户端添加Cookie
 public void add(HttpServletResponse response,String name,String value)
 {
  try
  {
   response.addCookie(new Cookie(name,value));
  }
  catch(Exception e)
  {
  }
 }
 
 //Get 方法,获得客户端的Cookie
 public String get(HttpServletRequest request,String name)
 {
  if(cookie_get.length==0)
  {
   cookie_get = request.getCookies();
  }
  String returnStr="Null";
  try
  {
   for(int i=0;cookie_get!=null && i<cookie_get.length;i++)
   {
    if(cookie_get[i].getName().equals(name))
    {
     returnStr= java.net.URLDecoder.decode(cookie_get[i].getValue().toString());
     break;
    }
   }
 
   return returnStr;
  }
  catch(Exception e)
  {
   return returnStr;
  } 
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值