java - get cookie value by name in spring mvc

JavaSpring MvcCookies

Java Problem Overview


I'm working on a java spring mvc application. I have set a cookie in one of my controller's methods in this way:

@RequestMapping(value = {"/news"}, method = RequestMethod.GET)
public ModelAndView news(Locale locale, Model model, HttpServletResponse response, HttpServletRequest request) throws Exception {
    
    ...
    response.setHeader("Set-Cookie", "test=value; Path=/");
    ...
    
    modelAndView.setViewName("path/to/my/view");
    return modelAndView;
}

This is working fine and I can see a cookie with name test and value "value" in my browser console. Now I want to get the cookie value by name in other method. How can I get value of test cookie?

Java Solutions


Solution 1 - Java

The simplest way is using it in a controller with the @CookieValue annotation:

@RequestMapping("/hello")
public String hello(@CookieValue("foo") String fooCookie) {
    // ...
}

Otherwise, you can get it from the servlet request using Spring org.springframework.web.util.WebUtils

WebUtils.getCookie(HttpServletRequest request, String cookieName)

By the way, the code pasted into the question could be refined a bit. Instead of using #setHeader(), this is much more elegant:

response.addCookie(new Cookie("test", "value"));

Solution 2 - Java

private String getCookieValue(HttpServletRequest req, String cookieName) {
    return Arrays.stream(req.getCookies())
            .filter(c -> c.getName().equals(cookieName))
            .findFirst()
            .map(Cookie::getValue)
            .orElse(null);
}

Solution 3 - Java

You can also use org.springframework.web.util.WebUtils.getCookie(HttpServletRequest, String).

Solution 4 - Java

Spring MVC already gives you the HttpServletRequest object, it has a getCookies() method that returns Cookie[] so you can iterate on that.

Solution 5 - Java

private String extractCookie(HttpServletRequest req) {
	        for (Cookie	c : req.getCookies()) {
		       if (c.getName().equals("myCookie"))
			       return c.getValue();
	           }
	        return null;
	    }

Solution 6 - Java

Cookie doesnt have method to get by value try this

Cookie cookie[]=request.getCookies();
Cookie cook;
String uname="",pass="";
if (cookie != null) {
for (int i = 0; i < cookie.length; i++) {
	cook = cookie[i];
	if(cook.getName().equalsIgnoreCase("loginPayrollUserName"))
			uname=cook.getValue();
	if(cook.getName().equalsIgnoreCase("loginPayrollPassword"))
			pass=cook.getValue();					
}    
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhamedView Question on Stackoverflow
Solution 1 - JavameskobalazsView Answer on Stackoverflow
Solution 2 - JavaottercoderView Answer on Stackoverflow
Solution 3 - JavaryanpView Answer on Stackoverflow
Solution 4 - JavabekceView Answer on Stackoverflow
Solution 5 - JavaPadiView Answer on Stackoverflow
Solution 6 - JavaVishnu KatpureView Answer on Stackoverflow