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
import
//.. @RequestMapping ( "/hello.html" ) public
@CookieValue ( "foo" ) //.. } |
In above code snippet we defined a controller method hello() which is mapped to URL /hello.html. Also we bind the parameter String
using
fooCookie@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: at at at at at at |
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
import
//.. @RequestMapping ( "/hello.html" ) public
@CookieValue (value "foo" , "hello" ) //.. } |
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
import
import
import
//.. @RequestMapping ( "/hello.html" ) public
response.addCookie( new
"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 new
"foo" , "bar" ); //bake foo.setMaxAge( 1000 ); //set response.addCookie(foo); //put |
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:
- Spring MVC 3.2.6.RELEASE
- Java 6
- Eclipse
- Maven 3
Following is the project structure.
Create and copy following file contents in the project structure.
Maven configuration: pom.xml
< project
= "http://maven.apache.org/POM/4.0.0"
= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 > < 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 > <!-- < 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 > <!-- < 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
= "1.0"
= "UTF-8" ?> < web-app
= "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee"
= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee id = "WebApp_ID"
= "2.5" > < display-name >Spring 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
= "1.0"
= "UTF-8" ?> < beans
= "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/context http://www.springframework.org/schema/mvc < context:annotation-config
< context:component-scan
= "net.viralpatel.spring"
< bean
= "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver" > < property
= "viewClass" value = "org.springframework.web.servlet.view.JstlView"
< property
= "prefix"
= "/WEB-INF/jsp/"
< property
= "suffix"
= ".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
<%@ < html > < head > < title >Spring title > </ head > < body > < h1 >Spring h1 > Page b > b > </ body > </ html > |
This JSP displays the hit counter. It prints the counter value using tag${cookie.hitCounter.value}
.
Spring Controller: HelloController.java
package
import
import
import
import
import
@Controller public
@RequestMapping (value "/hello.htm" ) public
@CookieValue (value "hitCounter" , "0" ) HttpServletResponse // hitCounter++; // Cookie new
"hitCounter" , response.addCookie(cookie); // return
; } } |
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
parameter. Notice how we mapped
hitCounterjava.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)
Related Articles
- Spring
@RequestHeader Annotation example - Spring
MVC Exception Handling using @ControllerAdvice annotation - Spring
3 MVC Interceptor tutorial with example - Spring
MVC Flash Attribute tutorial with example - Change
spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename) - Spring
MVC Multiple File Upload example - Spring
3 MVC: Handling Forms in Spring 3.0 MVC
Spring MVC Cookie example的更多相关文章
- spring mvc +cookie+拦截器功能 实现系统自动登陆
先看看我遇到的问题: @ResponseBody @RequestMapping("/logout") public Json logout(HttpSession session ...
- spring mvc 用cookie和拦截器实现自动登录(/免登录)
Cookie/Session机制详解:http://blog.csdn.net/fangaoxin/article/details/6952954 SpringMVC记住密码功能:http://blo ...
- Spring学习笔记之五----Spring MVC
Spring MVC通常的执行流程是:当一个Web请求被发送给Spring MVC Application,Dispatcher Servlet接收到这个请求,通过HandlerMapping找到Co ...
- Http请求中Content-Type讲解以及在Spring MVC中的应用
引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值 ...
- Spring MVC 学习总结(一)——MVC概要与环境配置
一.MVC概要 MVC是模型(Model).视图(View).控制器(Controller)的简写,是一种软件设计规范,用一种将业务逻辑.数据.显示分离的方法组织代码,MVC主要作用是降低了视图与业务 ...
- spring笔记2 spring MVC的基础知识2
2,spring MVC的注解驱动控制器,rest风格的支持 作为spring mvc的明星级别的功能,无疑是使得自己的code比较优雅的秘密武器: @RequestMapping处理用户的请求,下面 ...
- spring笔记1 spring MVC的基础知识1
1,spring MVC的流程 优秀的展现层框架-Spring MVC,它最出彩的地方是注解驱动和支持REST风格的url. 流程编号 完成的主要任务 补充 1 用户访问web页面,发送一个htt ...
- spring mvc基础配置
web.xml 配置: <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> ...
- 使用Spring MVC 实现 国际化
使用Spring MVC 实现 国际化 博客分类: Spring 1. 版本 Spring 3.1 2. 配置 LocaleResolver LocaleResolver 是指 ...
随机推荐
- Android 使用动态载入框架DL进行插件化开发
如有转载,请声明出处: 时之沙: http://blog.csdn.net/t12x3456 (来自时之沙的csdn博客) 概述: 随着应用的不断迭代.应用的体积不断增大,项目越来越臃肿,冗余添 ...
- ListView上拉刷新和分页加载完整的Dome
很多人工作的过程中都会碰到ListView下拉刷新和分页加载,然后大多数公司都已经把框架写好了,大家直接用就可以了,有些人一直对这个事情处于迷茫状态,为了让大家对上拉刷新和分页加载有一个比较全面的认识 ...
- zIndex属性在IE中无效
在ie中他的子类的zindex就以父类为准: <!doctype html> <html> <head> <meta charset="utf-8& ...
- 循环调用修正sic86
create or replace procedure rebuild_sic86_wyl(pi_aac001 in number, po_fhz out varchar2, po_msg out v ...
- javaScript 网页特效 输出语句
大家好,我是小强老师,今天主要讲解 三个最为常用的输出语句. alert() 弹出警示框 window.alert(‘继续学习’); 完整的写法 效果如下: 因为alert 属于window 对象 ...
- 飞翔(LIS变形)
飞翔 时间限制:3000 ms | 内存限制:65535 KB 难度:4 描述 鹰最骄傲的就是翱翔,但是鹰们互相都很嫉妒别的鹰比自己飞的快,更嫉妒其他的鹰比自己飞行的有技巧.于是,他们决定举办一场 ...
- shu_1548 悟空问题(大哥,主妖怪抓走的朋友!)
http://202.121.199.212/JudgeOnline/problem.php?cid=1078&pid=17 分析: 直接暴力了.. . 代码: #include <s ...
- iOS viewController添加导航条以及返回跳转选择
给单独的viewcontroller或者在Appdelegate的主页面添加导航条,只要在viewcontroller上添加navigationcontroller,在添加此navigationcon ...
- stm32内部的CAN总线
功能概述: bxCAN是基本扩展CAN(Basic Extended CAN)的缩写,它支持CAN协议2.0A和2.0B:它的设计目标是以最小的CPU负载来高效处理大量的报文.它也支持报文发送的优先级 ...
- Arduino 入门程序示例之一排 LED(2015-06-11)
概述 最简单的一个 LED 的实验之后,自然是增加几个 LED,咱排成一排来玩吧.最后,再把一排的 LED 排成一个 8 字来玩——七段数码管. 示例程序 流水灯 第一个出场的肯定是经典的流水灯,也叫 ...