- Notifications
You must be signed in to change notification settings - Fork21
A simple Java API for handling cookies
License
js-cookie/java-cookie
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A simple Java API for handling cookies
- Supports Java 8+, Servlet 2.2+
- Unobtrusive JSON Data Binding support
- RFC 6265 compliant
- Enablecustom decoding
Include the maven dependency in yourpom.xml:
<dependency> <groupId>com.github.js-cookie</groupId> <artifactId>java-cookie</artifactId> <version>0.0.2</version></dependency>
If you don't use Maven you can build the artifact from this repository, by installinggit SCM,Maven and executing the commands below:
$ git clone https://github.com/js-cookie/java-cookie.git$cd java-cookie$ mvn install -P simpleThe artifact will be created inside thejava-cookie/target folder.
Create a cookie, valid across the entire site
Cookiescookies =Cookies.initFromServlet(request,response );cookies.set("name","value" );
Create a cookie that expires 7 days from now, valid across the entire site:
Cookiescookies =Cookies.initFromServlet(request,response );cookies.set("name","value",Attributes.empty() .expires(Expiration.days(7 ) ));
Create an expiring cookie, valid to the path of the current page:
Cookiescookies =Cookies.initFromServlet(request,response );cookies.set("name","value",Attributes.empty() .expires(Expiration.days(7 ) ) .path("" ));
Read cookie:
Cookiescookies =Cookies.initFromServlet(request,response );cookies.get("name" );// => "value"cookies.get("nothing" );// => null
Read all available cookies:
Cookiescookies =Cookies.initFromServlet(request,response );Map<String,String>all =cookies.get();// => {name=value}
Delete cookie:
Cookiescookies =Cookies.initFromServlet(request,response );cookies.remove("name" );
Delete a cookie valid to the path of the current page:
Cookiescookies =Cookies.initFromServlet(request,response );cookies.set("name","value",Attributes.empty() .path("" ));cookies.remove("name" );// fail!cookies.remove("name",Attributes.empty().path("path" ) );// removed!
IMPORTANT! when deleting a cookie, you must pass the exact same path, domain and secure attributes that were used to set the cookie, unless you're relying on thedefault attributes.
java-cookie provides unobtrusive JSON storage for cookies with data binding.
When creating a cookie, you can pass a few supported types instead of String in the value. If you do so, java-cookie will store the stringified JSON representation of the value usingjackson databind.
Consider the following class that implements theCookieValue interface:
publicclassPersonimplementsCookieValue {privateintage;publicPerson(intage ) {this.age =age; }publicintgetAge() {returnage; }}
And the following usage:
Cookiescookies =Cookies.initFromServlet(request,response );cookies.set("name",newPerson(25 ) );
When reading a cookie with the defaultget() api, you receive the string representation stored in the cookie:
Cookiescookies =Cookies.initFromServlet(request,response );Stringvalue =cookies.get("name" );// => "{\"age\":25}"
If you pass the type reference, it will parse the JSON into a new instance:
Cookiescookies =Cookies.initFromServlet(request,response );Personadult =cookies.get("name",Person.class );if (adult !=null ) {adult.getAge();// => 25}
This project isRFC 6265 compliant. All special characters that are not allowed in the cookie-name or cookie-value are encoded with each one's UTF-8 Hex equivalent usingpercent-encoding.
The only character in cookie-name or cookie-value that is allowed and still encoded is the percent% character, it is escaped in order to interpret percent input as literal.
To override the default cookie decoding you need to use aconverter.
The default cookie attributes can be set globally by setting properties of the.defaults() instance or individually for each call to.set(...) by passing anAttributes instance in the last argument. Per-call attributes override the default attributes.
Cookiescookies =Cookies.initFromServlet(request,response );cookies.defaults() .secure(true ) .httpOnly(true );cookies.set("name","value",Attributes.empty() .httpOnly(false )// override defaults);
Define when the cookie will be removed. Value can be anExpiration.days() which will be interpreted as days from time of creation, ajava.util.Date or anorg.joda.time.DateTime instance. If omitted, the cookie becomes a session cookie.
Default: Cookie is removed when the user closes the browser.
Examples:
DateTimedate_2015_06_07_23h38m46s =newDateTime(2015,6,7,23,38,46 );Cookiescookies =Cookies.initFromServlet(request,response );cookies.set("name","value",Attributes.empty() .expires(Expiration.date(date_2015_06_07_23h38m46s ) ));cookies.get("name" );// => "value"cookies.remove("name" );
Define the path where the cookie is available.
Default:/
Examples:
Cookiescookies =Cookies.initFromServlet(request,response );AttributesvalidToTheCurrentPage =Attributes.empty().path("" );cookies.set("name","value",validToTheCurrentPath );cookies.get("name" );// => "value"cookies.remove("name",validToTheCurrentPath );
Define the domain where the cookie is available
Default: Domain of the page where the cookie was created
Examples:
Cookiescookies =Cookies.initFromServlet(request,response );cookies.set("name","value",Attributes.empty().domain("sub.domain.com" ) );cookies.get("name" );// => null (need to read at "sub.domain.com")
ABoolean indicating if the cookie transmission requires a secure protocol (https)
Default: No secure protocol requirement
Examples:
Cookiescookies =Cookies.initFromServlet(request,response );AttributessecureCookie =Attributes.empty().secure(true );cookies.set("name","value",secureCookie );cookies.get("name" );// => "value"cookies.remove("name",secureCookie );
ABoolean indicating if the cookie should be restricted to be manipulated only in the server.
Default: The cookie can be manipulated in the server and in the client
Examples:
Cookiescookies =Cookies.initFromServlet(request,response );AttributeshttpOnlyCookie =Attributes.empty().httpOnly(true );cookies.set("name","value",httpOnlyCookie );cookies.get("name" );// => "value"cookies.remove("name",httpOnlyCookie );
Define whether your cookie should be restricted to a first party or same-site context
Default: not set
Note that more recent browsers are making "Lax" the default value even without specifying anything here.
Examples:
Cookiescookies =Cookies.initFromServlet(request,response );cookies.set("name","value",Attributes.empty().sameSite("Lax" ) );cookies.get("name" );// => "value"
Create a new instance of the api that overrides the default decoding implementation.
All methods that rely in a proper decoding to work, such asremove() andget(), will run the converter first for each cookie.
The returning String will be used as the cookie value.
Example from reading one of the cookies that can only be decoded using the Javascriptescape function:
// document.cookie = 'escaped=%u5317';// document.cookie = 'default=%E5%8C%97';Cookiescookies =Cookies.initFromServlet(request,response );CookiesescapedCookies =cookies.withConverter(newCookies.Converter() {@OverridepublicStringconvert(Stringvalue,Stringname )throwsConverterException {ScriptEnginejavascript =newScriptEngineManager().getEngineByName("JavaScript" );if (name.equals("escaped" ) ) {try {returnjavascript.eval("unescape('" +value +"')" ).toString(); }catch (ScriptExceptione ) {thrownewConverterException(e ); } }returnnull; }});escapedCookies.get("escaped" );// => 北escapedCookies.get("default" );// => 北escapedCookies.get();// => {escaped=北, default=北}
Instead of passing a converter inline, you can also create a custom strategy by implementing theConverterStrategy interface:
classCustomConverterimplementsConverterStrategy {@OverridepublicStringconvert(Stringvalue,Stringname )throwsConverterException {returnvalue; }}
Cookiescookies =Cookies.initFromServlet(request,response );CookiescookiesWithCustomConverter =cookies.withConverter(newCustomConverter() );
Check out theContributing Guidelines.
About
A simple Java API for handling cookies
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.