Java Save Cookie__javaee

Source: Internet
Author: User

More articles Please enter: my open Source network

Many times the application needs to use cookies, such as shopping sites, save the shopping cart, there is a common login, save a week or six months, and so on, are to use cookies, the following describes the Java cookies in the save.

The 1.Cookie class is under the Javax.servlet.http package.


2. The method of constructing the class.

Cookies (string name, String value)
Constructs a cookie with a specified name and value.

Constructs a cookie based on the specified "name" and "value", which is like a key value pair in the map (this is, of course, my personal understanding).


3. As mentioned above, the method of constructing the cookie class begins with the creation of the cookie object.

Suppose I am now logged in, the account number and password are stored in the MyUser class, respectively, username and password.

Cookie cookie = new Cookie ("My_user", username+ "-" +password); Here I use "-" to separate the account and password, of course, you can also use the way you like to separate.


4. Set the time the cookie is saved.

setmaxage(int expiry)
Sets The maximum age of the cookies in seconds.

Maximum age of cookies set in seconds; here is my time in seconds, so if we keep it for a week, we'll calculate it.

int Seconds=7*24*60*60;//cookie Save time

Cookie.setmaxage (seconds);

5. Add cookies.

Response.addcookie (cookie); But you first have to get the response object and then add it through it.

6. Well, cookies are created like this.

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.