js/jsp How to manipulate cookies

Source: Internet
Author: User
Tags set cookie setcookie

Recent projects have used the automatic login feature to use cookies.

I. Cookie introduction The browser communicates with the Web server using the HTTP protocol, while the HTTP protocol is a stateless protocol. That is, when a user makes a page request, the Web server simply responds, and then closes the connection to that user. So when a request is sent to a Web server, whether or not it is the first visit, the server treats it as if it were the first time, which is a bad thing to imagine.     To compensate for this flaw, Netscape has developed a cookie that is an effective tool to keep a user's identifying information, a means by which a Web server stores information on a visitor's hard disk through a browser.     It is a small, plain text message that the server sends to the browser.     Definition: A cookie is a small amount of named data stored by a Web browser that is associated with a particular Web page and site. A text file in which a cookie is actually associated with a website and a Web page that holds certain information about the user.

Second, the properties of the cookie in addition to the name and value, each cookie has four optional attributes: 1.expires: Specifies the lifetime of the cookie.     By default, cookies are temporary and the browser is disabled. 2.path: It specifies a Web page that is associated with a cookie.         The default is in the same directory as the current page of the page in effect.     If path is set to "/", it is visible to all pages of the site.     3.domain: Set the cookie valid domain name, if the path is set to "/", the domain is set to ". Sohu.com", then all pages of a.sohu.com and b.sohu.com can access this cookie. 4.secure: Boolean value that specifies how cookies are transmitted on the network. By default, cookies are unsafe and can be transmitted via an unsecured, normal HTTP protocol, and if the cookie is set to be secure, it will only be transmitted when the browser and server are connected through HTTPS or other security protocols.

Third, the cookie operation cookie can use Javascipt to operate, also may use the JSP to operate. Below to everyone I wrote a few examples, I believe you can see it: 1.javascript operation:
<script language= "JavaScript" >
Set Cookie,cookie validity Time not GMT time (milliseconds from January 1, 1970 temporary)
For example, you can set Setcookie ("Password", "12345", (3600000*24*180)), 180 valid
function Setcookie (name, value, expires) {
var expdate = new Date ();
Expdate.settime (Expdate.gettime () + expires);
Document.cookie = name + "=" + Escape (value) +
"; Expires= "+ expires.togmtstring () +"; path=/";
}

Obtain a cookie value based on the cookie name
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 unescape (document.cookie.substring (offset, end));
}
Else
Return "";
}

Delete a cookie
function Deletecookie (name) {
var expdate = new Date ();
Expdate.settime (Expdate.gettime ()-(3600 *24* 1000 * 1));
Setcookie (Name, "", expdate);
}

Check if this cookie exists
function Checkcookie (cookiename,cookievalue) {
if (GetCookie (cookiename) ==cookievalue) {
return true;
}else{
return false;
}
}
</script>

2.jsp operation: There is a Cookie class in Java: Javax.servlet.http.Cookie


Read the general class of the cookie, with cookie[] to do the parameters to pass a constructor function;
Package com.test;
Import javax.servlet.http.*;
public class Comcookie {
Private cookie[] cookies;
Private cookie Cookie;
Public Comcookie (cookie[] cs) {
cookies = CS;
}
/**
* Through CookieName, get cookievalue, if not this cookie returns the default value
* @param cookiename
* @param defaultvalue
* @return
*/
public string Getcookievalue (string cookiename,string defaultvalue) {
for (int i=0; i< cookies.length; i++) {
Cookie cookie = cookies[i];
if (Cookiename.equals (Cookie.getname ()))
Return (Cookie.getvalue ());
}
return (defaultvalue);
}
/**
* Class method, through CookieName, get Cookievalue
* @param cookies
* @param cookiename
* @param defaultvalue
* @return
*/
public static String Getcookievalue (cookie[] cookies,
String CookieName,
String DefaultValue) {
for (int i=0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (Cookiename.equals (Cookie.getname ()))
Return (Cookie.getvalue ());
}
return (defaultvalue);
}
}


JSP: (The following is from the network)

The JSP uses the following syntax format to create a cookie: Cookie cookie_name =new Cookie ("Parameter", "Value"); For example: Cookie Newcookie =new Cookie ("username", "Waynezheng"); Response.addcookie (Newcookie); Explanation: A JSP is a corresponding constructor cookie (Name,value) that invokes a cookie object to create a cookie with the appropriate name and value, and then Cookies can be added to the Set-cookie answer header via the HttpServletResponse Addcookie method, in this case the cookie object has two string arguments: Username,waynezheng. Note that both the name and the value cannot contain white space characters and the following characters: @:;? , " / [ ] ( ) =

Handling cookie properties See here, some friends ask again: I just know how to create a cookie what is the use? Yes, it's not enough to know how to create a cookie without knowing how to use it. In JSP, the program is to set various properties through COOKIE.SETXXX, using Cookie.getxxx to read the properties of the cookie, the main attributes of the cookie, and its methods are listed below for your reference: Read the cookie of the client

Type method Name Method explanation
String getcomment () returns a comment in the cookie that returns a null value if there is no comment.
String GetDomain () returns the domain name that the cookie applies to in the cookie. Use the GetDomain () method to instruct the browser to return the cookie to another server in the same domain, and usually the cookie is returned only to the server that is exactly the same name as the server that sent it. Note that the domain name must start with a point (for example,. yesky.com)
int Getmaxage () returns the maximum time, in seconds, before the cookie expires.
String GetName () returns the name of the cookie. The name and value are the two parts that we always care about, the author will introduce getname/setname in detail later.
String GetPath () returns the path to which the cookie applies. If you do not specify a path, the cookie is returned to all pages in the same directory as the current page and its subdirectories.
Boolean getsecure () returns a true value if the browser sends a cookie via a security protocol, or False if the browser uses a standard protocol.
String GetValue () returns the value of the cookie. The author will also introduce getvalue/setvalue in detail later.
int GetVersion () returns the protocol version that the cookie complies with.
void Setcomment (String purpose) Sets the comment in the cookie.
void SetDomain (String pattern) sets the domain name that the cookie applies to in the cookie
void setmaxage (int expiry) is calculated in seconds to set the cookie expiration time.
void SetPath (String uri) specifies the path to which the cookie applies.
void SetSecure (Boolean flag) indicates the security protocol used by the browser, such as HTTPS or SSL.
The void SetValue (String newvalue) cookie is created after a new value is set.
void setversion (int v) Sets the protocol version that the cookie complies with.


Before the cookie is sent to the client, create a cookie and then send an HTTP Header using the Addcookie method. The JSP calls Request.getcookies () from the client read-in Cookie,getcookies () method to return an array of cookie objects corresponding to the contents of an HTTP request header. You only need to iterate through the elements of the array, call the GetName method to check the names of each cookie, find the target cookie, and then call the GetValue method on the cookie to get the value associated with the specified name.

For example
<%
String username=request.getparameter ("UserName");//obtained from the submitted HTML form, user name
Cookie Theusername=new Cookie ("username", username);//To create a cookie with "username", username value/pair
Response.addcookie (Theusername);
%>
..............
<%
Cookie mycookie[]=request.getcookies ();//Create an array of cookie objects
for (int n=0;n=cookie.length-1;i++);//Set up a loop to access each element of a cookie object array
Cookie newcookie= Mycookie[n];
if (Newcookie.getname (). Equals ("username")); Determines whether the value of an element is a value in username
{%>
Hello, <%=newcookie.getvalue ()%>!//If you find it, say hello to him.
<%}
%>
Set the existence time of the cookie, and delete the cookie in the JSP, use the setmaxage (int expiry) method to set the cookie's existence time,
The parameter expiry should be an integer. A positive value indicates that the cookie will expire after so many seconds. Note that this value is the maximum time that the cookie will be present,
Instead of the cookie's present time. A negative value indicates that the cookie will be deleted when the browser is closed. A value of 0 is the cookie to be deleted. Such as:
<%
Cookie Deletenewcookie=new Cookie ("Newcookie", null);
Deletenewcookie.setmaxage (0);
Deletenewcookie.setpath ("/");
Response.addcookie (Deletenewcookie);
%>

Js/jsp How to manipulate cookies

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.