396   Java SpringMVC

1, setCookie

// packages
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//function for setCookie
public static void setCookie(String cookieName, String value, int maxAge, HttpServletResponse response) {
    Cookie cookie = new Cookie(cookieName, value);
    // maxAge , cookie time , second
    cookie.setMaxAge(maxAge);
    response.addCookie(cookie);
}

2, getCookie

// function for getCookie
 public static String getCookie(String cookieName, HttpServletRequest request) {
	    String value = null;
	    Cookie[] cookies = request.getCookies();
	    if (cookies != null) {
	      int i = 0;
	      boolean cookieExists = false;
	      while (!cookieExists && i < cookies.length) {
	    	  log.info(cookies[i].getName()+":"+cookies[i].getValue());
	        if (cookies[i].getName().equals(cookieName)) {
	          cookieExists = true;
	          value = cookies[i].getValue();
	        } else {
	          i++;
	        }
	      }
	    }
	    return value;
}


3, removeCookie


// There is no method to remove cookie , just set cookie time to zero will be remove cookie 
// function for removeCookie
public static void setCookie(String cookieName, HttpServletResponse response) {
    Cookie cookie = new Cookie(cookieName, "");
    // maxAge , cookie time , second
    cookie.setMaxAge(0);
    response.addCookie(cookie);
}


 



Leave a Reply

Your email address will not be published. Required fields are marked *