Spring MVC Cookie example

spring mvc cookie example
In this post we will see how to access and modify http cookies of a webpage in Spring MVC framework.

Read Http Cookie in Spring MVC

Spring 3 MVC framework provides a very useful annotation @CookieValue to access data set within any http cookie. This annotation can be leverage to fetch the cookie value without getting into hassle of fetching cookies from http request and iterating through the list.

@CookieValue annotation can be used within Controller argument. It automatically bind the cookie value with method argument.

import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
public String hello(@CookieValue("foo") String fooCookie) {


In above code snippet we defined a controller method hello() which is mapped to URL /hello.html. Also we bind the parameter String fooCookie using @CookieValue annotation. When spring maps the request, it checks http for cookie with name “foo” and bind its value to String fooCookie.

No boiler plate code to iterate though list of cookies, just one line will do it all.

One thing worth noting here is that we have not defined any default value for the String fooCookie. If Spring does not find the cookie with name “foo” in http request, it will throw an exception: java.lang.IllegalStateException: Missing cookie value ‘foo’ of type [java language=”.lang.String”][/java]

java.lang.IllegalStateException: Missing cookie value 'foo' of type java.lang.String
	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.raiseMissingCookieException(HandlerMethodInvoker.java:796)
	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveCookieValue(HandlerMethodInvoker.java:684)
	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:357)
	at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
	at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)

In order to resolve this we must add default value to @CookieValue annotation so if Spring doesn’t find http cookie with that name, it binds the parameter with default value. Following is syntax for that:

import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
public String hello(
	@CookieValue(value = "foo", defaultValue = "hello") String fooCookie) {


We used value and defaultValue attribute of @CookieValue annotation. Thus if Spring doesn’t find any cookie with name ‘foo’ in http request, it binds the fooCookie parameter with value ‘hello’.

Setting Http Cookie in Spring MVC

We just saw how we can use @CookieValue annotation to auto-magically bind cookie value with a spring controller parameter.

Now let us see how to set a cookie in a Spring MVC based application. For this actually we will use HttpServletResponse class’s method addCookie(). Spring does not provide any fancy way to set http cookie because it’s already taken care by servlets HttpServletResponse class. All you need to do it to use just one method addCookie(). Spring MVC can be used to get the response object. Once we have this object it’s just piece of cake.

Consider below code:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

public String hello(HttpServletResponse response) {

	response.addCookie(new Cookie("foo", "bar"));



In above code we just bind HttpServletResponse object to Spring method controller and used its addCookie method to save new Cookie. That’s it. One line of code will do it. One thing worth noticing here is that you can set the cookie expire time using setMaxAge method on Cookie class.

Cookie foo = new Cookie("foo", "bar"); //bake cookie
foo.setMaxAge(1000); //set expire time to 1000 sec
response.addCookie(foo); //put cookie in response 

Complete Tutorial

Now we know the concept, let us use it and create a Spring MVC based application to track page hits. We will use Cookie to track page hit counter.

For this tutorial I will be using following tools and technologies:

  1. Spring MVC 3.2.6.RELEASE
  2. Java 6
  3. Eclipse
  4. Maven 3

Following is the project structure.

Create and copy following file contents in the project structure.

Maven configuration: pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
		<!-- Spring MVC  -->
		<!-- JSTL taglib -->

Maven configuration is simple. We just need Spring MVC and JSTL dependency.

Deployment description: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>Spring MVC Http Cookie</display-name>



Web.xml is quite simple too. We just need to configure Spring’s DispatcherServlet with *.htm url pattern.

Spring Configuration: spring-servlet.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<context:annotation-config />
	<context:component-scan base-package="net.viralpatel.spring" />

	<bean id="viewResolver"
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />

In spring-servlet.xml we just defined component scan to load @Controller classes. Also we defined a view resolver that will points to JSPs within /WEB-INF/jsp/ folder.

JSP file: hello.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
	<title>Spring MVC Cookie example</title>	

	<h1>Spring MVC Cookie example</h1>

	Page hit counter: <b> ${cookie.hitCounter.value} </b>


This JSP displays the hit counter. It prints the counter value using tag ${cookie.hitCounter.value}.

Spring Controller: HelloController.java

package net.viralpatel.spring;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

public class HelloController {

	@RequestMapping(value = "/hello.htm")
	public String hello(
			@CookieValue(value = "hitCounter", defaultValue = "0") Long hitCounter,
			HttpServletResponse response) {

		// increment hit counter

		// create cookie and set it in response
		Cookie cookie = new Cookie("hitCounter", hitCounter.toString());

		// render hello.jsp page
		return "hello";


The logic to fetch hit counter from cookie and set it back is written in HelloController. We used @CookieValue annotation to map hitCounter cookie to Long hitCounter parameter. Notice how we mapped java.lang.Long value. Spring automatically converts String from Cookie to Long value.


Open your favorite web browser and point to below URL:

Refresh page 2-3 times and see how hit counter value is incremented.

Download Source Code

Spring_Cookie_Example.zip (8 KB)

Get our Articles via Email. Enter your email address.

You may also like...


  1. Saranya says:

    my cookie value is reflected only on refresh and not on load.

Leave a Reply

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