Cookie reading and writing Java

Source: Internet
Author: User
Tags set cookie setcookie

There are two methods for reading and writing cookies: Program writing and JS writing,

 

1 written by program

For example:

/**
* Read cookie by name
*/
Public object getcookie (string name ){
Cookie [] cookie = request. getcookies ();
Object object = NULL;
For (INT I = 0; I <cookie. length; I ++)
{
If (cookie [I]. getname (). Equals (name) = true)
{
Object = cookie [I]. getvalue ();
Break;
}
}
Return object;
}
 
/**
* @ Name: Set the cookie name
* @ Value: Set the cookie value.
* @ Cookietime: Set the cookie survival time
* @ Domain: Set the cookie Domain Name
* @ Path: Set cookie
*/
Public void setcookie (string name, string value, long cookietime, string domain, string path ){
Cookie _ cookie = new cookie (name, value );
_ Cookie. setmaxage (cookietime );
_ Cookie. setdomain (domain );
_ Cookie. setpath (PATH );
Response. addcookie (_ cookie );
}

 

2. Write in JS:

Function fixcookiedate (date ){
VaR base = new date (0 );
VaR skew = base. gettime ();
If (Skew> 0) date. settime (date. gettime ()-skew );
}

Function setcookie (name, value, path, domain, secure ){
VaR expdates = new date ();
Fixcookiedate (expdates );
Expdates. settime (expdates. gettime () + (1*60*60*24*1000 ));
Document. Cookie = Name + "=" + (value) + (expdates )? "; Expires =" + expdates. togmtstring (): "") + (PATH )? "; Path =" + path: "") + (domain )? "; Domain =" + domain: "") + (secure )? "; Secure ":"");
}
Function getcookie (name ){
VaR search;

Search = Name + "="
Offset = Document. Cookie. indexof (Search)
If (offset! =-1 ){
Offset + = search. length;
End = Document. Cookie. indexof (";", offset );
If (END =-1)
End = Document. Cookie. length;
Return document. Cookie. substring (offset, end );
}
Else
Return "";
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.