Wednesday, September 25, 2013

Spring MVC and Cookie

In a common scenario, a cookie may be set on the client side using JavaScript

function setCookie() {
    var c_name = "javascriptCookie";
    var c_value = "this cookie was set by JavaScript";
    document.cookie=c_name + "=" + c_value;
}

Spring MVC can also write cookie while returning a page

@RequestMapping(value="/setcookie", method = RequestMethod.GET)
public String setCookie(HttpServletResponse response){
    response.addCookie(new Cookie("srpingCookie", "this cookie was set by Spring"));
    return "cookieIsSet";
}

To read cookies on Spring

// all the cookies can be seen here regardless of that the cookie was set on client side or server side
@RequestMapping(value="/readcookie", method = RequestMethod.GET)
public String showCookie(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null){
 for (Cookie cookie : cookies){
     System.out.println(cookie.getName() + " : " + cookie.getValue());
        }
    }
        
    ...
}

or

// mycookie must be available otherwise HTTP 400 occurs
// the cookie value will be unescape'd automatically
@RequestMapping(value="/readparticularcookie", method = RequestMethod.GET)
public String showDinoCookie(@CookieValue("mycookie") String cookie){
    System.out.println(cookie);

    ...
}

Reference
http://www.w3schools.com/js/js_cookies.asp

No comments:

Post a Comment