Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Feb 8, 2023. It is now read-only.
/java-cookiePublic archive

A simple Java API for handling cookies

License

NotificationsYou must be signed in to change notification settings

js-cookie/java-cookie

Repository files navigation

A simple Java API for handling cookies

Installation

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 simple

The artifact will be created inside thejava-cookie/target folder.

Basic Usage

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.

JSON Data Binding

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}

Encoding

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.

Cookie Attributes

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);

expires

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" );

path

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 );

domain

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")

secure

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 );

httpOnly

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 );

sameSite

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"

Converter

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() );

Contributing

Check out theContributing Guidelines.

About

A simple Java API for handling cookies

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp