Spring MVC Cookie Handling

Spring MVC

Cookies are small text files that are stored on client computers browser directory.
Cookies can be used for any of the following
1. Remember the information about the user who has visited a website, so that when the user returns to the website in future they can show information useful to the user,
Most of the shopping websites do this.
2. Track internet users web browsing.
3. Used in Session management.

Spring MVC Cookie handling

Spring MVC provides methods which we can use to create cookies or read data from cookies easily.

In this article we will see the tips for Spring MVC Cookie handling.

Read data from Cookie

Using the @Cookie annotaion we can define the cookie name that we want to read.

In the above example we may get an exception if the cookie with the given name is not found by Spring.

So It is recommended to add default a value to the cookie that we want to read to avoid any exceptions.

Store Data in Cookie

For storing the cookie value we use the response object.

 

I have created a simple example to read and write data in Cookie.
In this example we will have 2 links on the home page, one to read and other to write data in cookie.

If we first click on Read Cookie link, the default cookie value that was passed as param to the controller will be set in the cookie.

If we click on the Write Cookie link and then Read the Cookie value , then the new Cookie value will be displayed.
CookieController,java

 

OutPut
First Scenario : Clicking on Read Cookie without setting cookie value
Spring MVC Tutorial | Spring MVC Cookie Handling

Second Scenario : Clicking on Read Cookie after setting cookie value
Spring MVC Cookie Handling | Spring MVC Tutorial

Download the Source

SpringMVC-CookieHandling.zip

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn