Loading
 
What's Next: View All Tutorial →

Setting and retrieve Cookie in Spring MVC controller and JSP scriplet

A simple program to retrive cookie value in Spring MVC Controller   Retrieve Cookie in the Controller Part   import org.springframework.web.bind.annotation.CookieValue; @RequestMapping(value = {"getcityCookie"}) p...

Published Date: 11/01/2015  Last Modified Date: 11/01/2015    New Post



A simple program to retrive cookie value in Spring MVC Controller
 

Retrieve Cookie in the Controller Part

 
import org.springframework.web.bind.annotation.CookieValue;

 @RequestMapping(value = {"getcityCookie"})
    public String getCookie(@CookieValue(value = "cityNm", required = false) Integer cityId, ModelMap map,  HttpServletRequest request, HttpSession hs) {

       System.out.println(cityNm);

        return "responsejsppagename";
    }

required=false - By default, required is true, If set to false, it can accept null value, else exception will be thrown

@CookieValue - Cookie anotation in spring mvc version 4 above
 

Retrieve Cookie in the JSP Page

 
${cookie.cityNm.value}
 

Setting Cookie in the Controleer Part

 
 @RequestMapping(value = {"getcityCookie"})
    public String getCookie(ModelMap map,  HttpServletRequest request, HttpSession hs,  HttpServletResponse response) {
 

       Cookie cityCookie = new Cookie("cityNm", "Chennai");
       cityCookie.setMaxAge(3000000);
       cityCookie.setDomain("catchmycity.com");
       cityCookie.setPath(request.getContextPath() + Constants.FORWARD_SLASH);
       response.addCookie(cityCookie);


  return "responsejsppagename";
    }

setMaxAge - Duration in milliseconds

setPath is the website root path

setDomain - website domain. It can be subdomain (.catchmycity.com). It help to share all the site under the same domain


 
Awaiting for Administrator approval





Tags: Spring MVC

← Back to list


Related Post




×