key words: cookie 保留历史记录 登陆记录
很多时候用session觉得挺方便的,今天突然发现自己竟然几乎没用过cookie,呵呵,有点意思。正好碰到一个登陆页面,需要用户选择站点类型,觉得每次都让用户选择有点不合理,毕竟一个用户常用的就一个,所以决定用cookie记录下这个站点,下次登陆的时候可以直接显示.
效果如下:
/**
* 从cookie里读取指定Name 对应的值
* 如果没有返回空 null
* @param cookieName
* @param request
* @param decode :编码
* @return String
*/
public static String getCookieValue(String cookieName, HttpServletRequest request,String decode) {
if(null == cookieName || cookieName.trim().length() ==0) return "";
Cookie cookies[] = request.getCookies();
Cookie sCookie = null;
String sname = null;
String svalue = null;
if (null != cookies && cookies.length > 0) {
for (int i = 0; i < cookies.length; i++) {
sCookie = cookies[i];
sname = sCookie.getName();
if (cookieName.equals(sname)) {
try {
svalue = java.net.URLDecoder.decode(sCookie.getValue(),decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
break;
}
}
}
return svalue ;
}
/**
* 设置cookie
* @param cookieName
* @param cookieValue
* @param maxAge
* @param response
* @paramencode :编码
*/
public static void setCookieValue(String cookieName,String cookieValue,
int maxAge,HttpServletResponse response,String encode) {
if(null == cookieName || cookieName.trim().length() ==0) return ;
Cookie cookie = null;
try {
cookie = new Cookie(cookieName, java.net.URLEncoder.encode(cookieValue,encode));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}