Servlet--cookie

Source: Internet
Author: User

Session Technology

1.cookie
2.session

Sessions (session)

1. What is a session?
A session can be simply understood as: A user opens a browser to a Web site, clicks multiple hyperlinks, accesses multiple Web resources on the server, and then closes the browser, the whole process is called a session.

For example, call, I get through the phone, as long as the phone does not hang, this session is not over.

2. What are some of the issues to be addressed during the session?
Each user in the process of using the browser and the server session, will inevitably produce some data, the server to find a way to save the data for each user.

For example, when multiple users click a hyperlink to purchase a product from a servlet, the server should find a way to keep each user's purchases in place, so that when the user points out the servlet, the checkout servlet can get the user to checkout for the user's respective purchase.

Question: is this data saved in the request line?
Answer: Definitely not!

techniques for saving sessions-cookie

To ponder a question:
1. Sometimes, when you visit a website, you can see the time you last logged in to the site, and note that the time of the last login of different users is certainly not the same, how is this achieved?

A way to save a user's logon time using a database
After you have learned cookies, you can use cookies to implement

2. When you visit a shopping site, you will be able to see the products that you have visited, but also different users have viewed the product is certainly not the same, how is this achieved?

This function, often do not need to login to be able to prompt, obviously not saved on the server side, that is, can not be implemented through the database. So make sure you use cookies.

3. How to save the login username and password in the computer, the next time you log in do not need to re-enter?

The solution to all of these features: cookie technology

1. What is a cookie?

Cookies are client-side technology, and the server writes each user's data to the user's respective browser in the form of a cookie. When users use a browser to access Web resources on the server, they take their own data. In this way, the Web resource handles the user's own data.

The server saves the user's information on the client, such as login name, password, etc... is a cookie.
This information is like cookies, the amount of data is not large, the server can be read from the client when needed.

The cookie principle is as follows:

Write the servlet code Createcookie.java, save the cookie information: Username=gavin, we can see the packet capture situation:

Write the servlet code Readcookie.java, read the cookie information, at this time the packet capture situation:

What can 2.cookie be used for?
  • Save information such as last logon time
  • Save the user name, password, and do not have to log back in at a certain time
  • Record the user's preferences for visiting the site (e.g., background music, what is the background color of the page)
  • Personalization of the website, such as the service of the customized website, content.
Use of 3.cookie
    1. Cookies are created on the server side.

    2. Cookies are stored on the browser side of the

    3. The life cycle of a cookie can be cookie.setMaxAge() set by method, in seconds.

      Special emphasis: If Setmaxage is not set, the cookie does not exist when the browser is closed

The creation code for the cookie is this:

//创建cookienew Cookie("username""gavin");// 设置cookie的生命周期为1个小时cookie.setMaxAge(3600);// 把cookie信息回写给浏览器// Set-Cookie:username=gavin; Expires=Sun, 08-May-2016 11:35:55 GMTresponse.addCookie(cookie);
The read code is this:
// cookie会自动跟着request传递过来// 读取所有cookie信息,之后再选出自己需要的cookieCookie[] cookies = request.getCookies();for(Cookie cookie:cookies){    String name = cookie.getName();    String value = cookie.getValue();    out.println("cookie的名字:"+name+"<br>");    out.println("cookie的值:"+value+"<br>");}
4.cookie can be shared by multiple browsers

But in fact, because each browser saves cookies in different ways and paths, it is not possible to do different browser sharing cookies

5. How to understand: we can think of cookies as a table
name String Value String

One question: What happens if a cookie has a duplicate name?
Answer: If the duplicate name is replaced with the new cookie value

6. A Web application can hold multiple Cookie7.cookie stored in plaintext, so it is less secure. If you want to improve security, we can save it by encrypting it.

You can use the MD5 algorithm: In the future we have to use encryption password, in the authentication password when the user entered the password, MD5 encryption, and then to the database to verify.

* * Example: Save user logon time: * * Improve user management system, use cookies to save the last time a user logged in, for the next login display. Add the following code to the user's main interface:
//First login promptString welcome ="You are the first to log in"; String Lasttime =NULL;//Last access timecookie[] cookies = request.getcookies (); for(Cookie cookie:cookies) {//cookie is saved in the following way: value =lasttime-user id,vlue= logon time    ///For example, lasttime-123:2016-05-08 20:08:08    if(("lasttime-"+user.getid ()). Equals (Cookie.getname ())) {lasttime = Cookie.getvalue (); Break; }}if(Lasttime! =NULL) {welcome ="Last Logon time:"+lasttime;}//Update cookies, log the current logon time, and write back to the client for the next logon promptSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Cookie cookie =NewCookies ("lasttime-"+user.getid (), Sdf.format (NewDate ())); Cookie.setmaxage (3600* -*7); Response.addcookie (cookie);

You can see the results of the operation:

4. Summarize cookie-related functions

1.public Cookie(String name,String value)

2. setValue methods and getValue methods

3. setMaxAge methods and getMaxAge methods

4. getName Methods

How to write back cookies

addCookiemethod is provided by the response interface, which adds a corresponding Set-cookie message header to the HTTP response header

How to obtain cookies

GetCookies method, provided by the request interface, to obtain the cookie submitted by the client

5.cookie in-depth discussion
    1. A cookie can only hold string information

    2. A web app can send multiple cookies to a single browser, and a browser can store cookies provided by multiple web apps
      Note, however, that a browser generally allows only 300 cookies, with a maximum of 20 cookies per site, and a limit of 4 per cookie, so the cookie will not be stuffed with your hard drive and will not be used as a "denial of service" attack.

3.cookie The default life cycle is session level (that is, stored in the browser's memory), the user exits the browser is deleted, of course, you can setMaxValue(int expiry) set the cookie life cycle, if set to 0, is to instruct the browser to delete the cookie, and require re-addcookie to take effect.

4. Note that when you delete a cookie, the path must be the same, or it will not be deleted.

5. How are cookies stored in Chinese?
When storing:

String val = java.net.URLEncoder.encode("小明","utf-8"new Cookie("name",val);

When it is removed:

String val = cookie.getValue();val = java.net.URLDecoder.decode(val,"utf-8");out.println("name:"+val);

Servlet--cookie

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.