Friday, January 18, 2008

Cookies in JSF

  // create cookies
HttpServletResponse httpServletResponse =
(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
Cookie cookie = new Cookie("cookieKey", "cookieValue");
cookie.setMaxAge(365);
cookie.setComment("A Comment");
httpServletResponse.addCookie(cookie);

// get cookies
HttpServletRequest httpServletRequest =
(HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
Cookie[] cookies = httpServletRequest.getCookies();
if (cookies != null) {
for(int i=0; i<cookies.length; i++){
if (cookies[i].getName().equalsIgnoreCase("cookieKey")){
String cookieValue = cookies[i].getValue();
}
}
}

2 comments:

David said...

Thanks for this little code nugget. I really helped me out.

Unknown said...

Thanks, just what I was looking for!