How to use cookies with spring

Writting a cookie

You can make the browser to save a cookie by adding it to the response like is shown in this snipplet:

public class GeneralController {	
    @RequestMapping(value = "/mycookie/{type}", produces = "text/html")
    public String changeType(@PathVariable("type") String type, 
                             Model uiModel,
                             HttpServletResponse response){
    	Cookie c=new Cookie("mode", type);  
    	return "redirect:/";

The property c.setPath(“/”); is done because we want that cookie valid over the whole web domain.

Reading from a controller

If you want to read the value of a cookie from a controller you can use the @CookieValue annotation:

public @ResponseBody String fileuploader(@PathVariable("fileid") String id, 
    HttpServletRequest request,
    HttpServletResponse response,
    @CookieValue("mode") String cookieMode) 
    throws IOException{    	    	                       
    		if (!"expectedCookieValue".equals(cookieMode)){
		    //Do something

In this case the String variable cookieMode will have the content of the cookie mode, if that cookie is not present its value will be null

Reading from JSTL

It is also possible to read the cookie from JSTL and change the view accordingly. Here is an example of how to do it:

<c:if test="${cookie.mode.value!='expectedCookieValue'}">
   <p> The cookie has the expected Value</p>

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s