本文实例讲述了Java读写Cookie记录的方法。分享给大家供大家参考。具体如下:
写Cookie ,cookie的value可以使String, list , map,int :
1
2
3
4
5
6
7
|
Cookie usernameCookie = new Cookie( "username_" + schoolId, encodedUsername);
usernameCookie.setMaxAge( 60 * 60 * 24 * 365 );
response.addCookie(usernameCookie);
//设置useriCookie--用于心教育的猜你喜欢课程
Cookie userIdCookie = new Cookie( "userId_" + schoolId, userId);
userIdCookie.setMaxAge( 60 * 60 * 24 * 365 );
response.addCookie(userIdCookie);
|
读Cookie:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
String userId= null ;
Cookie[] cookies = request.getCookies();
//cookies不为空,则清除
if (cookies!= null )
{
for (Cookie cookieTemp : cookies){
String cookieIdentity = cookieTemp.getName();
//查找身份串
if (cookieIdentity.equals( "userId_" +schoolId))
{
userId=cookieTemp.getValue();
}
}
}
|
希望本文所述对大家的java程序设计有所帮助。