@CookieValue and @RequestHeaders


No more extra code required to get the Cookie value and Header values in spring 3...

Spring 3 introduced below annotations to get the cookie values and header values

1) @CookieValue
2) @RequestHeader

@CookieValue : It allows a method parameter to be bound to the value of an HTTP cookie.

Example :
Let's assume the cookie (mycookie) has been received with an http request, below is the code to get the cookie in controller
  
@RequestMapping(value = "/success.do",method = RequestMethod.POST)
public String submitForm(@CookieValue("mycookie") String cookie)  {
 System.out.println("my cookie"+cookie);
 ....................
} 
If you want to set the cookie in Http response, then you can use below code
  
@RequestMapping(method = RequestMethod.GET)
 public String registrationForm(ModelMap model, HttpServletResponse response) {
  Cookie myCookie = new Cookie("myCookie", "val");
  response.addCookie(myCookie);
   ...................
 }
More about @CookieValue (http://static.springsource.org)

@RequestHeader : It allows a method parameter to be bound to a request header,  @RequestHeader annotation which indicates that a method parameter should be bound to a web request header, below is the code to get the value of host in request header.
  
@RequestMapping("/success.do")
public void submitForm(@RequestHeader("Host") String host )  {
  //...
}
More about @RequestHeader (http://static.springsource.org)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...