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;
//..
@RequestMapping("/hello.html")
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.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;
//..
@RequestMapping("/hello.html")
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 responseobject.
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;
//..
 
@RequestMapping("/hello.html")
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 itsaddCookie 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"
>
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.viralpatel.spring</groupId>
    <artifactId>Spring_Cookie_example</artifactId>
    <packaging>war</packaging>
    <version>1.0.0-SNAPSHOT</version>
    <name>SpringMVCCookie</name>
    <properties>
        <org.springframework.version>3.2.6.RELEASE</org.springframework.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <compileSource>1.6</compileSource>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <!--
Spring MVC  -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <!--
JSTL taglib -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.1.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>springcookie</finalName>
    </build>
    <profiles>
    </profiles>
</project>

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>
    <welcome-file-list>
        <welcome-file>hello.htm</welcome-file>
    </welcome-file-list>
 
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
 
</web-app>

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

Spring Configuration: spring-servlet.xml

<?xml 

version
="1.0"

encoding
="UTF-8"?>
<beans

xmlns
="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property

name
="viewClass"
            value="org.springframework.web.servlet.view.JstlView"

/>
        <property

name
="prefix"

value
="/WEB-INF/jsp/"

/>
        <property

name
="suffix"

value
=".jsp"

/>
    </bean>
     
     
</beans>

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" %>
<html>
<head>
    <title>Spring
MVC Cookie example</
title>   
</head>
<body>
 
    <h1>Spring
MVC Cookie example</
h1>
 
    Page
hit counter: <
b>
${cookie.hitCounter.value} </
b>
 
</body>
</html>

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;
 
@Controller
public

class

HelloController {
 
    @RequestMapping(value
=
"/hello.htm")
    public

String hello(
            @CookieValue(value
=
"hitCounter",
defaultValue =
"0")
Long hitCounter,
            HttpServletResponse
response) {
 
        //
increment hit counter
        hitCounter++;
 
        //
create cookie and set it in response
        Cookie
cookie =
new

Cookie(
"hitCounter",
hitCounter.toString());
        response.addCookie(cookie);
 
        //
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.

Demo

Open your favorite web browser and point to below URL:

http://localhost:8080/Spring_Cookie_Example/hello.htm

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

Download Source Code

Spring_Cookie_Example.zip
(8 KB)

Spring MVC Cookie example的更多相关文章

  1. spring mvc +cookie+拦截器功能 实现系统自动登陆

    先看看我遇到的问题: @ResponseBody @RequestMapping("/logout") public Json logout(HttpSession session ...

  2. spring mvc 用cookie和拦截器实现自动登录(/免登录)

    Cookie/Session机制详解:http://blog.csdn.net/fangaoxin/article/details/6952954 SpringMVC记住密码功能:http://blo ...

  3. Spring学习笔记之五----Spring MVC

    Spring MVC通常的执行流程是:当一个Web请求被发送给Spring MVC Application,Dispatcher Servlet接收到这个请求,通过HandlerMapping找到Co ...

  4. Http请求中Content-Type讲解以及在Spring MVC中的应用

    引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值 ...

  5. Spring MVC 学习总结(一)——MVC概要与环境配置

    一.MVC概要 MVC是模型(Model).视图(View).控制器(Controller)的简写,是一种软件设计规范,用一种将业务逻辑.数据.显示分离的方法组织代码,MVC主要作用是降低了视图与业务 ...

  6. spring笔记2 spring MVC的基础知识2

    2,spring MVC的注解驱动控制器,rest风格的支持 作为spring mvc的明星级别的功能,无疑是使得自己的code比较优雅的秘密武器: @RequestMapping处理用户的请求,下面 ...

  7. spring笔记1 spring MVC的基础知识1

    1,spring MVC的流程 优秀的展现层框架-Spring MVC,它最出彩的地方是注解驱动和支持REST风格的url.   流程编号 完成的主要任务 补充 1 用户访问web页面,发送一个htt ...

  8. spring mvc基础配置

    web.xml 配置: <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> ...

  9. 使用Spring MVC 实现 国际化

    使用Spring MVC 实现 国际化     博客分类: Spring   1. 版本 Spring 3.1   2. 配置 LocaleResolver     LocaleResolver 是指 ...

随机推荐

  1. 1410 - Consistent Verdicts(规律)

    1410 - Consistent Verdicts   PDF (English) Statistics Forum Time Limit: 5 second(s) Memory Limit: 32 ...

  2. Linux下which、whereis、locate、find 区别

    我们经常在linux要查找某个文件或命令,但不知道放在哪里了,可以使用下面的一些命令来搜索.which      查看可执行文件的位置 whereis    查看文件的位置 locate     配合 ...

  3. DataTable 用linq分组查询

    DataRow drt = null; var tlist = dt.Select("Atmbs LIKE '%" + d["Two_Code"] + &quo ...

  4. iOS 开发 Message Digest Algorithm 5(MD5加密)

    MD5的全称是Message Digest Algorithm 5(消息摘要算法第五版),是计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护.在90年代初由MIT Laboratory ...

  5. 内联函数 inline

    (一)inline函数(摘自C++ Primer的第三版) 在函数声明或定义中函数返回类型前加上关键字inline即把min()指定为内联. inline int min(int first, int ...

  6. 高质量程序设计指南C/C++语言——C++/C程序设计入门

    1.在C++/C中,全局变量(extern或static)存放在程序的静态数据区中,在程序进入main()之前创建,在main()结束之后销毁,因此在我们的代码中根本没有机会初始化它们,于是语言及其实 ...

  7. ZOJ 2853 Evolution 【简单矩阵快速幂】

    这道题目第二次看的时候才彻底理解了是什么意思 把题目转化为数学模型分析后就是 有一个初始序列, 有一个进化率矩阵 求的是初始序列 与进化率矩阵进行 m 次运算后, 初始序列最后一位的答案 那么显然,可 ...

  8. 2014 HDU多校弟九场I题 不会DP也能水出来的简单DP题

    听了ZWK大大的思路,就立马1A了 思路是这样的: 算最小GPA的时候,首先每个科目分配到69分(不足的话直接输出GPA 2),然后FOR循环下来使REMAIN POINT减少,每个科目的上限加到10 ...

  9. Dijkstra、Dij + heap、Floyd、SPFA、 SPFA + SLF Template

    Dijkstra in Adjacency matrix : int Dijkstra(int src,int tec, int n){ ]; ]; memset(done,,sizeof(done) ...

  10. 一致性算法--Paxos

    分布式一致性算法--Paxos Paxos算法是莱斯利·兰伯特(Leslie Lamport)1990年提出的一种基于消息传递的一致性算法.Paxos算法解决的问题是一个分布式系统如何就某个值(决议) ...