Table of Contents
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()
.
Code Block |
---|
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.
Code Block |
---|
WebResponse webResponse = |
To send and retrieve cookies, use the WebResponse
and WebRequest
objects, respectively. These in turn can be obtained from the RequestCycle
, which can be retrieved by calling the getRequestCycle
method on a Component
. Thus to create a cookie:
Code Block |
---|
((WebResponse)getRequestCycle().getResponse()).addCookie(new Cookie("cookieName", "cookieValue"));
|
and to retrieve all cookies:
Code Block |
---|
Cookie[] cookies = ((WebRequest)getRequestCycle().getRequest()).getCookies();
|
Alternatively, anywhere on the thread that is responding to a web request:
Code Block |
---|
((WebResponse)RequestCycle.get().getResponse()).addCookie(; // Create cookie and add it to the response Cookie cookie = new Cookie("cookieName", "cookieValue")); |
and similarly for retrieving cookies.
Finally, the casts can be avoided if you are within a subclass of WebPage
:
webResponse.addCookie(cookie); |
Advanced attributes of the cookie
Code Block |
---|
Cookie cookie = |
Code Block |
getWebRequestCycle().getWebResponse().addCookie(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 |