How to add cookie to JSF?

When I add a cookie as shown below:

FacesContext.getCurrentInstance().getExternalContext().addResponseCookie("Test", "Test", null); 

Then it works well, but the cookie becomes a session file with a maximum age of -1 .

When I try, as shown below:

 Map<String, Object> properties = new HashMap<>(); properties.put("domain", "test"); properties.put("maxAge", 31536000); properties.put("secure", false); properties.put("path","/"); FacesContext.getCurrentInstance().getExternalContext().addResponseCookie("Test", "Test", properties); 

Then I do not see the cookie anywhere. I do not understand why.

I am using Tomcat 7.

+6
cookies jsf-2
source share
2 answers

Try the following:

 public class CookieHelper { public void setCookie(String name, String value, int expiry) { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest(); Cookie cookie = null; Cookie[] userCookies = request.getCookies(); if (userCookies != null && userCookies.length > 0 ) { for (int i = 0; i < userCookies.length; i++) { if (userCookies[i].getName().equals(name)) { cookie = userCookies[i]; break; } } } if (cookie != null) { cookie.setValue(value); } else { cookie = new Cookie(name, value); cookie.setPath(request.getContextPath()); } cookie.setMaxAge(expiry); HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.addCookie(cookie); } public Cookie getCookie(String name) { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) facesContext.getExternalContext().getRequest(); Cookie cookie = null; Cookie[] userCookies = request.getCookies(); if (userCookies != null && userCookies.length > 0 ) { for (int i = 0; i < userCookies.length; i++) { if (userCookies[i].getName().equals(name)) { cookie = userCookies[i]; return cookie; } } } return null; } } 
+18
source share

Your specific case failed because the domain was set incorrectly. Cookies are domain specific. You cannot set cookies in another domain. If you do not specify a domain, it will be the default scope of the current request URI. Cookie#setDomain() is useful if you intend to set a cookie in a shared or other domain under . For example. if you have foo.example.com and bar.example.com , you can set cookies for another domain using this method or set .example.com (with a leading period!) for the domain to share a cookie between both subdomains .

So this should be in your particular case:

 String name = "cookiename"; String value = "cookievalue"; Map<String, Object> properties = new HashMap<>(); properties.put("maxAge", 31536000); properties.put("path", "/"); externalContext.addResponseCookie(name, URLEncoder.encode(value, "UTF-8"), properties); 

Please note that explicit path setting is very important if you intend to use a common web cookie, since it defaults to the current path, which, of course, will fail when it is set for the first time in a subfolder. Such a cookie will not be available in any parent folder. The other answer here above does not take this into account properly, as it unnecessarily and incorrectly reuses an existing cookie, rather than creating it completely new. See Also ao In the Java servlet, cookie.getMaxAge () always returns -1 .

Regarding getting the cookie in JSF, use ExternalContext#getRequestCookieMap() :

 Cookie cookie = (Cookie) externalContext.getRequestCookieMap().get(name); String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); // ... 

Please note that I encode / decode the URL of the cookie before setting / extracting, otherwise you would encounter problems, for example, in the following related questions: Why are cookie values ​​with spaces on the client side with quotes? and java.lang.IllegalArgumentException: control character in value or cookie attribute .

However, I agree that the JSF API is somewhat opaque regarding the search and setting of cookies. The JSF OmniFaces utility has several useful utility methods in the Faces utility class for a purpose that implicitly sets the correct default values ​​as cookie properties and URL encodes / decodes the value.

 // Getting a cookie value. String value = Faces.getRequestCookie(name); // Setting a session cookie in current path. Faces.addResponseCookie(name, value, -1); // Setting a session cookie in current domain. Faces.addResponseCookie(name, value, "/", -1); // Setting a (sub)domain-wide session cookie. Faces.addResponseCookie(name, value, ".example.com", "/", -1); // Setting a cookie with max age of 1 year in current domain. Faces.addResponseCookie(name, value, "/", (int) TimeUnit.DAYS.toSeconds(365)); // Removing a cookie from current domain. Faces.removeResponseCookie(name, "/"); 
+18
source share

All Articles