Details and simple examples of cookie in java

  • 2020-05-27 05:42:53
  • OfStack

cookie in java

The operation of Java to cookie is relatively simple. It mainly introduces how to set up cookie and read cookie, as well as how to set the life cycle of cookie and the path of cookie.

Create a non-lifecycle cookie, cookie that disappears as the browser closes, as shown below


HttpServletRequest
 request 
HttpServletResponse
 response
Cookie
 cookie = new Cookie("cookiename","cookievalue");
response.addCookie(cookie);

Let's create a life-cycle cookie and set its life-cycle


cookie
 = new Cookie("cookiename","cookievalue");
 
cookie.setMaxAge(3600);
 
// Set the path that is accessible under the project cookie
  If you don't set the path, only set the cookie The path and its subpaths are accessible 
 
cookie.setPath("/");
response.addCookie(cookie);

Here's how to read cookie. Read the cookie code as follows


Cookie[]
 cookies = request.getCookies();// So you can get it 1 a cookie An array of 
for(Cookie
 cookie : cookies){
  cookie.getName();//
 get the cookie name
  cookie.getValue();
//
 get the cookie value
}

Above is the basic operation of reading and writing cookie. We'd better do 1 encapsulation in practice, for example, add 1 cookie, we focus on cookie's name, value life cycle, so encapsulate 1 function, of course, pass in 1 response object, addCookie() code is as follows


/**
 *
  Set up the cookie
 *
 @param response
 *
 @param name cookie The name 
 *
 @param value cookie value 
 *
 @param maxAge cookie The life cycle   In seconds 
 */
public static void addCookie(HttpServletResponse
 response,String name,String value,int maxAge){
  Cookie
 cookie = new Cookie(name,value);
  cookie.setPath("/");
  if(maxAge>0) 
 cookie.setMaxAge(maxAge);
  response.addCookie(cookie);
}

When reading cookie, in order to facilitate our operation, we want to encapsulate 1 function. As long as we provide cookie's name, we can obtain value of cookie. With this idea, it is easy to think of encapsulating cookie into Map, so we do the following encapsulation


/**
 *
  Get by name cookie
 *
 @param request
 *
 @param name cookie The name 
 *
 @return
 */
public static Cookie
 getCookieByName(HttpServletRequest request,String name){
  Map<String,Cookie>
 cookieMap = ReadCookieMap(request);
  if(cookieMap.containsKey(name)){
    Cookie
 cookie = (Cookie)cookieMap.get(name);
    return cookie;
  }else{
    return null;
  } 
}
 
 
 
/**
 *
  will cookie Wrapped in Map inside 
 *
 @param request
 *
 @return
 */
private static Map<String,Cookie>
 ReadCookieMap(HttpServletRequest request){ 
  Map<String,Cookie>
 cookieMap = new HashMap<String,Cookie>();
  Cookie[]
 cookies = request.getCookies();
  if(null!=cookies){
    for(Cookie
 cookie : cookies){
      cookieMap.put(cookie.getName(),
 cookie);
    }
  }
  return cookieMap;
}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: