欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cookies的建立和清除

程序员文章站 2022-03-20 13:58:09
...
假设页面有个checkbox,name="remember",如果勾选了,就建立cookie,支持中文的话,还必须编码和解码操作

// ** 建立cookies
String rememberMe = request.getParameter("rememberMe");
log.debug("logincheckServlet current position >> request.getParameter[remeberMe] = "+rememberMe);
if("on".equals(rememberMe))
{
log.debug("logincheckServlet current position >> 建立cookies, start!");
String urlEncodeUserName = null;
try
{
// ** 吧中文名字编码
urlEncodeUserName = URLEncoder.encode(userName,"utf-8");
log.debug("logincheckServlet current position >> urlEncodeUserName = "+urlEncodeUserName);
}
catch (UnsupportedEncodingException e)
{
log.error("LoginCheck cp >> URLDecoder.encode() error!");
e.printStackTrace();
}

StringBuffer sb=new StringBuffer();
sb.append("username=");
sb.append(urlEncodeUserName);
sb.append("&password=");
sb.append(password);
Cookie cookie=new Cookie("userinfo",sb.toString());
cookie.setMaxAge(1800);
cookie.setPath("/");
//cookie.setDomain(".gicp.net");
response.addCookie(cookie);
log.debug("logincheckServlet current position >> 建立cookies, end!");
}


打算logout,清除一些相关记录

HttpSession session = request.getSession();
session.invalidate();
log.debug("LogoutServlet current position >> session.invalidate() 完成!");

// **
Cookie[] cookies=request.getCookies();
// ** 查找cookie
if(cookies!=null)
{
for(int i=0;i<cookies.length;i++)
{

Cookie cookie=cookies[i];
String cName=cookie.getName();
log.debug("LogoutServlet current position >> cookie.getName() = "+cName);
if(cName.equals("userinfo") )
{
//cookie.setValue(null);
cookie.setPath("/");
cookie.setMaxAge(0);
//cookie.setMaxAge(-1);
response.addCookie(cookie);
log.debug("LogoutServlet current position >> 找到cName.equals【userinfo】并删除!");
}
}
}
log.debug("LogoutServlet current position >> 完成清除cookies的!");
相关标签: .net