This Confluence has been LDAP enabled, if you are an ASF Committer, please use your LDAP Credentials to login. Any problems file an INFRA jira ticket please.

Child pages
  • Dealing with cookies
Skip to end of metadata
Go to start of metadata


What are cookies

Cookies are small pieces of key-value informations stored in the browser. They are always store as a strings = both key and value are strings.

Retrieve cookie(s)

You can retrieve cookies from the WebRequest object, that can be retrieved from the RequestCycle

Quick hint:  RequestCycle can be obtained by calling Component#getRequestCycle() or anywhere on the thread, that is responding to a web-request by calling RequestCycle.get().

WebRequest webRequest = (WebRequest)RequestCycle.get().getRequest();
 
// Variant A: Get cookie with specified name
Cookie cookie = webRequest.getCookie("cookieName");
 
// Variant B: Get all cookies at once
List<Cookie> cookiesList = webRequest.getCookies();

Create and save cookies

You can ask web-browser to store cookies, by adding cookie into the WebResponse object, that can be retrieved from the RequestCycle.

WebResponse webResponse = (WebResponse)RequestCycle.get().getResponse();
 
// Create cookie and add it to the response
Cookie cookie = new Cookie("cookieName", "cookieValue");
webResponse.addCookie(cookie);

Advanced attributes of the cookie

Cookie cookie = new Cookie("cookieName", "cookieValue");
cookie.setPath("/articles");                              // Cookies will be stored and sent only for URLs under http://server/articles
cookie.setMaxAge(7*24*60*60);                             // 7 days; expressed in seconds
cookie.setComment("my comment for this cookie");          // Any comment you want
  • No labels