Java method to read and write Cookie records

  • 2020-04-01 03:53:03
  • OfStack

This article illustrates how Java can read and write Cookie records. Share with you for your reference. The details are as follows:

Write Cookie. The value of Cookie can be String, list, map,int:


Cookie usernameCookie = new Cookie("username_" + schoolId, encodedUsername);
usernameCookie.setMaxAge(60 * 60 * 24 * 365);
response.addCookie(usernameCookie);
//Set useriCookie- guess you like the course for mind education
Cookie userIdCookie = new Cookie("userId_" + schoolId, userId);
userIdCookie.setMaxAge(60 * 60 * 24 * 365);
response.addCookie(userIdCookie);

Read the cookies:


HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
String userId=null;
Cookie[] cookies = request.getCookies();
//Cookies are not empty, then clear
if(cookies!=null)
{
 for(Cookie cookieTemp : cookies){
   String cookieIdentity = cookieTemp.getName();
   //Find identity string
   if(cookieIdentity.equals("userId_"+schoolId))
   {
    userId=cookieTemp.getValue();
   }
 }
}

I hope this article has been helpful to your Java programming.


Related articles: