Session and cookie


SessionTracking is a common technique in Web programs, which is used to track the dataTracking the user‘s entire session. Cookie and session are two common session tracking techniques.Cookies determine the user’s identity by recording information on the clientSession determines the user’s identity by recording information on the server

This chapter will systematically talk about cookie and session mechanism, and compare and explain when cookie can’t be used and when session can’t be used.

one point one   Cookie mechanism

In programs, session tracking is very important. theoretically,All requests of a user should belong to the same session, while all requests of another user should belong to another session, and the two cannot be confused. For example, any product purchased by user a in the supermarket should be placed in the shopping cart of user A. no matter when user a purchases it, it belongs to the same session. It cannot be placed in the shopping cart of user B or user C. It does not belong to the same session.

Web applications use HTTP protocol to transfer data.HTTP is a stateless protocol. Once the data exchange is completed, the connection between the client and the server will be closed, and a new connection needs to be established to exchange data again. This means that the server cannot track the session from the connection. That is to say, when user a purchases a product and puts it into the shopping cart, the server can no longer judge whether the purchase belongs to user a’s session or user B’s session. To track the session, a mechanism must be introduced.

Cookie is such a mechanism. It can make up for the lack of HTTP protocol stateless. Before the appearance of session, almost all websites used cookie to track the session.

1.1.1   What is cookie

Cookie, which means “cookie”, isProposed by W3CIt is a mechanism developed by the Netscape community. At present, cookie has become a standard, and all mainstream browsers such as ie, Netscape, Firefox, opera support cookie.

Because HTTP is a stateless protocol, the server can’t know the identity of the client only from the network connection. What shall I do? JustIssue a pass to clients, each one. No matter who visits, they must carry their own pass. In this way, the server can confirm the identity of the client from the pass. That’s how cookies work

A cookie is actually a small piece of text information. The client requests the server. If the server needs to record the user’s status, it uses response to issue a cookie to the client browser. The client browser will save the cookie. When the browser requests the website again, the browser submits the requested URL together with the cookie to the server. The server checks the cookie to identify the user status. The server can also modify the contents of the cookie as needed.

Session and cookie

It’s easy to see the cookies issued by a website. Enter in the browser address barjavascript:alert (document. cookie)It’s OK (you need a network to view it). JavaScript script will pop up a dialog box to display the contents of all cookies issued by the website, as shown in Figure 1.1.

Session and cookie

Figure 1.1   Cookies issued by Baidu website

The dialog box in Figure 1.1 shows the cookie of Baidu website. The first line of baiduid records the author’s identity Helloween vsfei, but Baidu uses a special method to encrypt the cookie information.

Note: the cookie function requires browser support.

If the browser does not support cookies (such as most browsers in mobile phones) or if cookies are disabled, the cookie function will fail.

Different browsers use different ways to save cookies.

IE browser will save a text file in the folder of “C: documents and settings your user name cookies”, and a text file will save a cookie.

1.1.2   Record the number of user visits

In Java, cookie is encapsulated as javax. Servlet. Http. Cookie class. Each cookie is an object of the cookie class. The server operates the client cookie by operating the cookie class object. adoptRequest. Getcookie() gets all the cookies submitted by the client(returned in the form of cookie [] array),Set the cookie to the client through response. Addcookie (cookie cookie).

Cookie object uses key value attribute pair to save user state, one cookie object saves one attribute pair, and one request or response uses multiple cookies at the same time. Because the cookie class is located under the package javax. Servlet. Http. *, there is no need to import this class in JSP.

1.1.3   Cookie can’t cross domain

Many websites use cookies. For example, Google will issue cookies to clients, and Baidu will also issue cookies to clients. Will browsers visit Google with cookies issued by Baidu? Or can Google modify the cookie issued by Baidu?

The answer is No.Cookie can’t cross domain. According to the cookie specification, a browser visiting Google will only carry Google’s cookie, not Baidu’s cookie. Google can only operate Google’s cookie, but not Baidu’s cookie.

Cookies are managed by the browser on the client side. The browser can ensure that Google can only operate Google’s cookie, but not Baidu’s cookie, so as to ensure the privacy and security of users. The basis for a browser to determine whether a website can operate another website cookie is the domain name. The domain names of Google and Baidu are different, so Google can’t operate the cookie of Baidu.

It should be noted that although the website is different from the website They belong to Google, but their domain names are different. They can’t operate each other’s cookies.

Note: users log on to the website After that, you will find that the login information is still valid when you visit, but ordinary cookies can’t. That’s because Google did something special. Cookies will be treated similarly later in this chapter.

1.1.4   Unicode encoding: saving Chinese

Chinese characters are different from English characters,Chinese belongs to Unicode characters, accounting for 4 characters in memory, while English belongs to ASCII characters, accounting for only 2 bytes in memory. When using Unicode characters in cookies, you need to encode Unicode characters, otherwise it will be garbled.

Tip: Chinese can only be encoded in cookie. Generally, UTF-8 coding is enough. Chinese encoding such as GBK is not recommended because browsers do not necessarily support it, and JavaScript does not support it.

1.1.5   Base64 encoding: saving binary images

Cookies can use not only ASCII and Unicode characters, but also binary data. For example, digital certificates are used in cookies to provide security. Binary data also needs to be encoded.

Note: This program is only used to show that binary content can be stored in cookie, not practical. Because the server will carry cookies every time the browser requests, the content of cookies should not be too much, otherwise the speed will be affected. The content of cookies should be small and refined.

1.1.6   Set all properties of cookie

In addition to name and value, cookies have several other common attributes. Each attribute corresponds to a getter method and a setter method. All properties of cookie class are shown in Table 1.1.

Table 1.1   Cookie common properties

genus   nature   name

Description     Narration

String name

The name of the cookie. Once a cookie is created, the name cannot be changed

Object value

The value of the cookie. If the value is a Unicode character, you need to encode the character. If the value is binary, Base64 encoding is required

int maxAge

The time, in seconds, that the cookie failed. If it is a positive number, the cookie is invalid after maxage seconds. If it is a negative number, the cookie is a temporary cookie. Closing the browser will be invalid, and the browser will not save the cookie in any form. If 0, the cookie is deleted. The default is – 1

boolean secure

Whether the cookie is only transmitted using the secure protocol. Security protocol. Security protocols include HTTPS, SSL, etc., which encrypt data before transmitting data on the network. The default is false

String path

The usage path of the cookie. If it is set to / sessionweb /, only programs with contextpath of / sessionweb can access the cookie. If it is set to ‘/’, the cookie can be accessed by contextpath under this domain name. Note that the last character must be ‘/’

String domain

The domain name that can access the cookie. If it is set to “. Google. Com”, all domain names ending with “Google. Com” can access the cookie. Note that the first character must be “.”

String comment

A description of the use of the cookie. This description is displayed when the browser displays cookie information

int version

The version number used by the cookie. 0 means following Netscape’s cookie specification, 1 means following W3C’s RFC 2109 specification

1.1.7   Validity period of cookie

The maxage of the cookie determines the validity period of the cookie, and the unit is second. Read and write maxage attribute through getmaxage() method and setmaxage (int maxage) method in cookie.

If the maxage property is a positive number, the cookie will automatically expire after maxage seconds. The browser will persist the cookie with positive maxage, that is, write it to the corresponding cookie file. No matter whether the client has shut down the browser or the computer, the cookie is still valid when the client logs in to the website as long as it is still before maxage seconds. The cookie information in the following code will always be valid.

Cookie cookie = new Cookie(“username”,”helloweenvsfei”);    // New cookie

cookie.setMaxAge(Integer.MAX_ VALUE);            // Set the lifecycle to max_ VALUE

response.addCookie(cookie);                    // Output to client

If maxage is negative, it means that the cookie is only valid in this browser window and the sub windows opened by this window. After closing the window, the cookie will be invalid. Cookies with negative maxage are temporary and will not be persisted or written to cookie files. The cookie information is stored in the browser memory, so the cookie disappears when the browser is closed. The default maxage value for cookies is – 1.

If maxage is 0, the cookie is deleted. Cookie mechanism does not provide a way to delete cookies, so it can achieve the effect of deleting cookies by setting the instant invalidation of the cookie. Invalid cookies will be removed from the cookie file or memory by the browser,

For example:

Cookie cookie = new Cookie(“username”,”helloweenvsfei”);    // New cookie

cookie.setMaxAge(0);                           // Set the life cycle to 0 and cannot be negative

response.addCookie(cookie);                    // This sentence must be carried out

The cookie operation method provided by the response object has only one add operation (cookie cookie).

If you want to modify the cookie, you can only use a cookie with the same name to cover the original cookie to achieve the purpose of modification. When deleting, you only need to change maxage to 0.

Note: when reading a cookie from the client, other attributes, including maxage, are unreadable and will not be submitted. When a browser submits a cookie, it only submits the name and value attributes. The maxage attribute is only used by the browser to determine whether the cookie has expired.

1.1.8   Modification and deletion of cookie

Cookies do not provide modification or deletion. If you want to modify a cookie, you just need to create a new cookie with the same name and add it to the response to cover the original cookie.

If you want to delete a cookie, you just need to create a new cookie with the same name, set maxage to 0, and add it to the response to cover the original cookie. Note that it’s zero, not negative. Negative numbers mean something else. Readers can verify through the above example and set different properties.

Note: when modifying or deleting a cookie, all attributes of the new cookie, except value and maxage, such as name, path and domain, should be exactly the same as the original cookie. Otherwise, the browser will be regarded as two different cookies and will not be covered, resulting in the failure of modification and deletion.

1.1.9   Cookie’s domain name

Cookies are not cross domain. domain name Issued cookies will not be submitted to the domain name Go. This is determined by the privacy security mechanism of cookies. Privacy security mechanism can prevent websites from illegally obtaining cookies from other websites.

Under normal circumstances, two secondary domain names under the same primary domain name, such as And can’t use cookies interactively because their domain names are not exactly the same. If you want all secondary domain names under to use the cookie, you need to set the domain parameter of the cookie, for example:

Cookie cookie = new Cookie(“time”,”20080808″); // New cookie

cookie.setDomain(“”);            // Set domain name

cookie.setPath(“/”);                               // set up path

cookie.setMaxAge(Integer.MAX_ VALUE);                // Set validity period

response.addCookie(cookie);                       // Output to client

Readers can modify the hosts file of C: windowssystem32driverseetc to configure multiple temporary domain names, and then use setcookie.jsp program to set the domain attribute of cross domain cookie verification.

Note: the domain parameter must start with a dot (“.). In addition, two cookies with the same name but different domains are two different cookies. If you want two websites with completely different domain names to share a cookie, you can generate two cookies. The domain attribute is two domain names and output them to the client.

1.1.10   Cookie path

The domain attribute determines the domain name of the cookie, while the path attribute determines the contextpath of the cookie. For example, if only programs under / sessionweb / are allowed to use cookies, you can write as follows:

Cookie cookie = new Cookie(“time”,”20080808″);     // New cookie

cookie.setPath(“/session/”);                           // set up path

response.addCookie(cookie);                           // Output to client

When set to ‘/’, all paths are allowed to use cookies. The path attribute needs to end with the symbol /. Two cookies with the same name but the same domain are also two different cookies.

Note: the page can only get the cookie of the path to which it belongs. For example, / session / test / a.jsp cannot get a cookie with the path of / session / ABC /. Be careful when using.

1.1.11   Security properties of cookies

HTTP protocol is not only stateless, but also insecure. The data using HTTP protocol can be directly transmitted on the network without any encryption, which may be intercepted. Using HTTP protocol to transmit confidential content is a hidden danger. If you don’t want cookies to be transmitted in non secure protocols such as HTTP, you can set the secure property of cookies to true. Browsers only transmit such cookies in security protocols such as HTTPS and SSL. The following code sets the secure property to true:

Cookie cookie = new Cookie(“time”, “20080808”); // New cookie

cookie.setSecure(true);                           // Set security properties

response.addCookie(cookie);                        // Output to client

Tip: the secure attribute can’t encrypt the cookie content, so it can’t guarantee the absolute security. If high security is needed,It is necessary to encrypt and decrypt the cookie content in the program to prevent leakage.

1.1.12   JavaScript operation cookie

Cookies are stored on the browser side, so the browser has the prerequisite to operate cookies. Browsers can use script programs such as JavaScript or VBScript to operate cookies. Here, JavaScript is taken as an example to introduce the commonly used cookie operation. For example, the following code will output all the cookies on this page.


Because JavaScript can read and write cookies at will, some good people want to use JavaScript programs to spy on users’ cookies on other websites. However, this is futile. W3C organizations have long been aware of the security risks brought by JavaScript’s reading and writing cookies, and have taken precautions against them. W3C standard browsers will prevent JavaScript from reading and writing cookies that do not belong to their own websites. In other words, the JavaScript program of website a reads and writes the cookie of website B without any result.

1.1.13   Case: permanent login

If the user is surfing the Internet on his home computer, he can remember his login information when he logs in. He doesn’t need to log in again when he visits next time, so he can visit directly. The implementation method isSave the login information such as account number and password in the cookie, control the validity period of the cookie, and verify the login information in the cookie next time.

There are many ways to save login information. The most direct thing is to keep the user name and password in the cookie, and check the user name and password in the cookie when you visit the database next time. This isIt is a more dangerous choice. Generally, important information such as password is not saved in cookie

alsoOne is to encrypt the password and save it in the cookie, decrypt it and compare it with the database next time. This scheme is slightly safer. If you don’t want to save the password, you can also save the login time stamp to the cookie and database, and then only verify the user name and login time stamp.

These solutions need to query the database when verifying the account.

This example will adopt another scheme, which only queries the database once when logging in, and will not query the database when accessing and verifying the login information later. The way to achieve this isAfter the account is encrypted according to certain rules, it is saved in the cookie together with the account. The next time you visit, you only need to judge whether the encryption rules of the account are correct. In this example, the account is saved in a cookie named account, and the account and the key are encrypted with MD1 algorithm and saved in a cookie named SSID. During verification, verify whether the encrypted account and key in the cookie are equal to the SSID in the cookie. The relevant codes are as follows:

Code 1.8   loginCookie.jsp

Session and cookie; ” Copy code “)

<%@ page language=”java”pageEncoding=”UTF-8″ isErrorPage=”false” %>

<%! // JSP method private static final string key=“ :[email protected] “; // Key public final static string calcmd1 (stringss) {/ / MD1 encryption algorithm string s = SS = = null? “: ss; // If NULL, return null

char hexDigits[] = { '0','1', '2', '3', '4', '1', '6', '7', '8', '9',
   'a', 'b', 'c', 'd', 'e', 'f' };                        //  Dictionaries

try { byte[] strTemp =s.getBytes(); // Get byte

MessageDigestmdTemp = MessageDigest.getInstance("MD1"); //  Get MD1

   mdTemp.update(strTemp); //  Update data byte [] MD = mdtemp. Digest()// Encryption int j = md.length// Length after encryption

    char str[] = newchar[j * 2]; //  New string array int k = 0// Counter K for (int i = 0; i< j;  I + +) {// loop output byte, byte0 = MD [i];

     str[k++] =hexDigits[byte0 >>> 4 & 0xf];

     str[k++] =hexDigits[byte0 & 0xf];


    return newString(str); //  Encrypted string

   } catch (Exception e){return null; }

} %>

<% request.setCharacterEncoding(“UTF-8”); // Set request encoding

response.setCharacterEncoding("UTF-8"); //  Set response code string action = request. Getparameter ("action")// Get the action parameter if ("login". Equals (action)) {// if it is a login action, string account = request. Getparameter ("account")// Get the account parameter string password = request. Getparameter ("password")// Get the password parameter int timeout = newinteger (request. Getparameter ("timeout"))// Get the timeout parameter string SSID = calcmd1 (account + key)// The account and key are encrypted with MD1 and saved


    CookieaccountCookie = new Cookie("account", account); //  New cookie

   accountCookie.setMaxAge(timeout); //  Set validity period


    Cookie ssidCookie =new Cookie("ssid", ssid); //  New cookie

   ssidCookie.setMaxAge(timeout); //  Set validity period


   response.addCookie(accountCookie); //  Output to client

   response.addCookie(ssidCookie); //  Output to the client // re request the page. The parameter contains a timestamp, which prevents the browser from caching the page content

   response.sendRedirect(request.getRequestURI() + "?" + System.


}Else if ("logout". Equals (action)) {// if it is a logout action


    CookieaccountCookie = new Cookie("account", ""); //  New cookie, content is empty

   accountCookie.setMaxAge(0); //  Set the validity period to 0, delete


    Cookie ssidCookie =new Cookie("ssid", ""); //  New cookie, content is empty

   ssidCookie.setMaxAge(0); //  Set the validity period to 0, delete

   response.addCookie(accountCookie); //  Output to client

   response.addCookie(ssidCookie); //  Output to the client // re request the page. The parameter contains a timestamp, which prevents the browser from caching the page content

   response.sendRedirect(request.getRequestURI() + "?" + System.


} boolean login = false; //  Log in string account = null// Account string SSID = null// SSID identifies if (request. Getcookies ()= Null) {// for (cookie Cookie: request. Getcookies()) {// traverse cookie if (cookie. Getname(). Equals ("account") // if cookie name is

           account = cookie.getValue(); //  Save account content if (cookie. Getname(). Equals ("SSID") // if SSID

           ssid = cookie.getValue(); //  Save SSID content


} if(account !=  null && ssid != Null) {// if neither account nor SSID are empty

    login =ssid.equals(calcMD1(account + KEY)); //  If the encryption rules are correct, it is considered to have logged in

} %>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01Transitional//EN”>

<legend><%= login ? " Welcome back ":" please log in to "% > < / legend > first

    <% if (login) {% > welcome, ${cookie. Account. Value}& nbsp;

       <a href="${ pageContext.request.requestURI }? Action = logout "> logout</a>

    <% } else {%>

    <formaction="${ pageContext.request.requestURI }?action=login" method="post">


           < tr > < td > account number:</td>

               <td><input type="text"name="account" style="width:
               200px; "></td>


           < tr > < td > password:</td>

               <td><inputtype="password" name="password"></td>



               <td>Validity period:</td>

               <td>< inputtype = "radio" name = "timeout" value = - 1 "checked > it will be invalid after closing the browser < br / > < input type =" radio "name =" timeout "value = <% = 30 * 24 * 60 * 60% >" > 30 days
               Internal valid < br / > < input type = "radio" name = "timeout" value= 
               "<%= Integer.MAX_ Value% > "> permanent < br / > < / td > < / TR >


               <td>< input type = "submit" value = "login" class= 




    <% } %>

Session and cookie; ” Copy code “)

When logging in, you can choose the validity period of the login information: it will be invalid when you close the browser, valid within 30 days or permanent. By setting the Cookie’s age attribute to achieve, pay attention to observe the code. The operation effect is shown in Figure 1.7.

Session and cookie

Figure 1.7   Permanent login

Tip: the most important part of the encryption mechanism is algorithm and key. Because of the irreversibility of MD1 algorithm, even if the user knows the account and the encrypted string, it is impossible to decrypt the key. Therefore, as long as the key and algorithm are well kept, the mechanism is secure.

one point two   Session mechanism

In addition to using cookies, session is often used in web applications to record client status.Session is a mechanism used by the server to record the state of the client, which is easier to use than cookie, and the correspondingIncrease the storage pressure of the server

1.2.1   What is a session

Session is another mechanism to record the client’s status. The difference is that cookies are saved in the client browser, while sessions are saved on the server. When the client browser accesses the server, the server records the client information in some form on the server. This is the session. When the client browser accesses again, it only needs to find the status of the client from the session.

ifCookie mechanism is to confirm the identity of the customer by checking the “pass” on the customer, then session mechanism is to confirm the identity of the customer by checking the “customer details” on the server. Session is equivalent to a client file created by the program on the server. When a client visits, he only needs to query the client file table.

1.2.2   Realize user login

The corresponding class of session is javax.servlet.http.httpsession. Each visitor corresponds to a session object, in which all the client’s status information is saved.The session object is created when the client first requests the server. Session is also a key value attribute pair, which reads and writes customer status information through getattribute (stringkey) and setAttribute (string key, objectvalue) methods. Get the session of the client through the request. Getsession() method in the servlet,

For example:

Session and cookie; ” Copy code “)

HttpSession session = request.getSession(); // Get session object

session.setAttribute(“loginTime”, new Date()); // Set properties in session

Out. Println (“login time: + (date) session. Getattribute (” logintime “))// Gets the session property

Session and cookie; ” Copy code “)

Request can also use getsession (Boolean create) to get the session. The difference is that if the client’s session does not exist, the request. Getsession () method will return null, while getsession (true) will create the session first and then return it.

Request must be used in servlet to get httpsession object programmatically, while session hidden object is built in JSP, which can be used directly. Session hidden objects are not available if <% @ page session = “false”% > is declared with. The following example uses session to record customer account information.

The source code is as follows:

Code 1.9   session.jsp

Session and cookie; ” Copy code “)

<%@ page language=”java” pageEncoding=”UTF-8″%>

< import=”com.helloweenvsfei.sessionWeb.bean.Person”/>

< import=”java.text.SimpleDateFormat”/>

< import=”java.text.DateFormat”/>

< import=”java.util.Date”/>


DateFormat dateFormat = newSimpleDateFormat("yyyy-MM-dd"); //  Date formatter% >

<% response.setCharacterEncoding(“UTF-8”); // Set request encoding

Person [] persons = {// basic data, saving the information of three people new person ("Liu Jinghua", "password1", 34, dateformat. Parse "
    ("1982-01-01")), new Person("Hello Kitty","hellokitty", 23, dateFormat.parse
    ("1984-02-21")), new Person("Garfield", "garfield_pass",23, dateFormat.parse

 };  String message = ""; //  Message to display if (request. Getmethod(). Equals ("post"))

{// if it is post login for (person person: persons)

    {// traverse the basic data to verify the account and password // if the user name is correct and the password is correct, if (person. Getname(). Equalsigniorecase (request. Getparameter ("user name")) & person. Getpassword(). Equals (request. Getparameter ("password"))

       {// login is successful. Save the user's information and login time to session

           session.setAttribute("person", person); //  Save login person

           session.setAttribute("loginTime", new Date()); //  Save login time              

           response.sendRedirect(request.getContextPath() + "/welcome.jsp");




    Message = "user name and password do not match, login failed."// Login failed

} %>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01Transitional//EN”>

<html>/ /… HTML code for a form form, code omitted, please see the CD-ROM with the book</html>

Session and cookie; ” Copy code “)

The login interface verifies the user’s login information. If the login is correct, save the user’s information and login time into session, and then go to welcome.jsp. Welcome. JSP gets information from session and displays user information.

Welcome.jsp code is as follows:

Code 1.10   welcome.jsp

Session and cookie; ” Copy code “)

<%@ page language=”java” pageEncoding=”UTF-8″%>


< import=”java.text.SimpleDateFormat”/>

< import=”java.text.DateFormat”/>

< import=”java.util.Date”/>


DateFormat dateFormat = newSimpleDateFormat("yyyy-MM-dd"); //  Date formatter% >

<% Person person =(Person)session.getAttribute(“person”); // Get the person date logintime of login = (date) session. Getattribute (“logintime”)// Get login time% > / /… Some HTML codes are slightly < Table >

< tr > < td > your name:</td>

               <td><%= person.getName()%></td>


           < tr > < td > login time:</td>

               <td><%= loginTime%></td>


           < tr > < td > your age:</td>

               <td><%= person.getAge()%></td>


           < tr > < td > your birthday:</td>

               <td><%=dateFormat.format(person.getBirthday()) %></td>



Session and cookie; ” Copy code “)

The running effect of the program is shown in Figure 1.8.

Session and cookie

Figure 1.8   Using session to record user information

Note that session in the program directly saves the person class object and date class object, which is more convenient to use than cookie.

When multiple clients execute the program, the server will save the session of multiple clients. When getting a session, you don’t need to declare whose session you want to get.The session mechanism determines that the current customer will only get their own session, but not someone else’s session. The sessions of each customer are also independent and invisible to each other

Tips: session is more convenient to use than cookie, but too many sessions are stored in the server memory, which will cause pressure on the server.

1.2.3   Session life cycle

The session is saved on the server side.In order to get higher access speed, the server usually puts session in memory. Each user will have a separate session. If the session content is too complex, it may lead to memory overflow when a large number of clients access the server. Therefore, the information in the session should be as concise as possible.

Session is automatically created when the user accesses the server for the first time. It should be noted that session will be created only when accessing JSP, servlet and other programs. Session will not be created only when accessing HTML, image and other static resources. If a session has not been generated, you can also use request. Getsession (true) to force the generation of a session.

After the session is generated, as long as the user continues to access, the server will update the last access time of the session and maintain the session. Every time a user visits the server, whether or not the session is read or written, the server thinks that the user’s session is “active” once.

1.2.4   Valid period of session

As more and more users will visit the server, so will sessions.To prevent memory overflow, the server will delete sessions that are not active for a long time from memory. This time is the session timeout. If the server is not accessed after the timeout period, the session will be invalid automatically.

The timeout of session is the maxinactive interval attribute, which can be obtained through the corresponding getmaxinactive interval() and modified through setmaxinactive interval (longinterval).

The session timeout can also be modified in web.xml. In addition, the session can be invalidated by calling the invalidate () method of the session.

1.2.5   Common methods of session

Session includes various methods, which are much more convenient to use than cookie. The common methods of session are shown in Table 1.2.

Table 1.2   Common methods of httpsession

square   method   name

Description     Narration

void setAttribute(String attribute, Object value)

Set the session property. The value parameter can be any Java object. Usually Java beans. Value information should not be too large

String getAttribute(String attribute)

Returns the session property

Enumeration getAttributeNames()

Returns the property name that exists in the session

void removeAttribute(String attribute)

Remove session property

String getId()

Returns the ID of the session. The ID is automatically created by the server and will not be repeated

long getCreationTime()

Returns the creation date of the session. The return type is long, which is often converted to date type, for example: date createtime = new date (session. Get creationtime())

long getLastAccessedTime()

Returns the last active time of the session. The return type is long

int getMaxInactiveInterval()

Returns the timeout of the session. The unit is seconds. If the session is not accessed after this time, the server thinks that the session is invalid

void setMaxInactiveInterval(int second)

Set the session timeout. The unit is seconds

void putValue(String attribute, Object value)

Not recommended. Replaced by setAttribute (string attribute, object value)

Object getValue(String attribute)

Not recommended. Replaced by getattribute (string attr)

boolean isNew()

Returns whether the session is newly created

void invalidate()

Disable the session

The default timeout of session in Tomcat is 20 minutes. Modify the timeout by setmaxinactive interval (int seconds). You can modify web.xml to change the default timeout of session. For example, 60 minutes:


<session-timeout>60</session-timeout> <!– Unit: minutes — >


Note: the unit of the < session timeout > parameter is minutes, while the unit of setmaxinactive interval (int s) is seconds.

1.2.6   Session requirements for browser

Although session is stored in the server and transparent to the client, its normal operation still needs the support of the client browser. This is because session needs to use cookie as an identifier. HTTP protocol is stateless, and session cannot judge whether it is the same client based on HTTP connection. Therefore, the server sends a cookie named jsessionid to the client browser, whose value is the ID of the session (that is, the return value of httpsession. Getid()). Session identifies the same user based on the cookie.

The cookie is automatically generated by the server, and its maxage attribute is generally – 1, which means that it is only valid in the current browser, and it is not shared among browser windows, so closing the browser will be invalid.

Therefore, when two browser windows of the same machine access the server, two different sessions will be generated. Except for the new window opened by links, scripts, etc. in the browser window (that is, not the window opened by double clicking the desktop browser icon, etc.). This kind of child window will share the cookie of the parent window, so it will share a session.

Note: the new browser window will generate a new session, except for the child window. The child window shares the session of the parent window. For example, when you right-click on the link and select “open in new window” in the pop-up shortcut menu, the child window can access the session of the parent window.

What if the client browser disable the cookie function or does not support cookies? For example, most mobile browsers do not support cookies. Java Web provides another solution: URL address rewriting.

1.2.7   URL address rewriting

URL address rewriting is a solution that does not support cookies for clients. The principle of URL address rewriting is to rewrite the ID information of the user session into the URL address. The server can parse the rewritten URL to get the session ID. In this way, even if the client does not support cookies, session can be used to record the user status. Httpservletresponse class provides encodeurl (string URL) to realize URL address rewriting, for example:


<a href="<%=response.encodeURL("index.jsp?c=1&wd=Java") %>"> 


This method will automatically determine whether the client supports cookies. If the client supports cookies, the URL will be output intact. If the client does not support cookies, the ID of the user session will be rewritten into the URL. The rewritten output might look like this:




That is, after the file name, the string “is added before the URL parameter; jsessionid=XXX”。 Where XXX is the ID of the session. Analysis shows that the added jsessionid string will not affect the file name of the request or the address bar parameters submitted. When the user clicks the link, the session ID will be submitted to the server through the URL, and the server obtains the session ID by parsing the URL address.

For page redirection, URL rewriting can be written as follows:

Session and cookie; ” Copy code “)






} %>

Session and cookie; ” Copy code “)

The effect is the same as response.encodeurl (string URL): if the client supports cookie, the original URL address will be generated; if cookie is not supported, the rewritten address with jsessionid string will be returned.

For WAP programs, because most mobile browsers do not support cookies, WAP programs use URL rewriting to track user sessions. For example, the mobile business street of UFIDA group.

Note: the basis for Tomcat to determine whether the client browser supports cookies is whether the request contains cookies. Although the client may support cookies, since no cookies will be carried in the first request (because no cookies can be carried), the rewritten URL address will still contain jsessionid. When the second access, the server has already written the cookie in the browser, so the rewritten URL address will not contain jsessionid.

1.2.8   Cookies are not allowed in session

Since most of the client browsers on WAP do not support cookies, it is better to prohibit session from using cookies and use URL rewriting uniformly. Java Web specification supports to disable cookies by configuration. Here is an example of how to disable cookies through configuration.

Open the meta-inf folder in the Webroot directory of the project session web (the same level as the WEB-INF folder, if not, create it), and open context.xml (if not, create it). The editing contents are as follows:

Code 1.11  / META-INF/context.xml

<?xml version=’1.0′ encoding=’UTF-8′?>

<Context path=”/sessionWeb”cookies=”false”>


Or modify the global conf / context.xml of Tomcat as follows:

Code 1.12   context.xml

Session and cookie; ” Copy code “)

<!– The contents of this file will be loaded for eachweb application –>

<Context cookies=”false”>

<!-- ...  Intermediate code is omitted -- >


Session and cookie; ” Copy code “)

After deployment, Tomcat will not automatically generate a cookie named jsesionid, and session will not use cookie as identification mark, but only rewritten URL address as identification mark.

Note: this configuration only forbids session to use cookie as identification mark, and it can’t prevent other cookies from reading and writing. In other words, the server will not automatically maintain the cookie named jsesionid, but the program can still read and write other cookies.

The difference between cookie and session

1. The cookie data is stored on the client’s browser, and the session data is stored on the server

In short, when you log in to a website, if the web server uses session, all the data will be saved on the server,

Each time the client requests the server, it will send the session of the current session_ According to the current session_ ID determines the corresponding user data flag to determine whether the user logs in or has certain permissions.

Since the data is stored on the server, you can’t forge it, but if you can get the session of a login user_ Using a special browser to forge the user’s request can also be successful.

session_ ID is randomly assigned when the server and client link, generally speaking, there will be no duplication, but if there are a large number of concurrent requests, there is no possibility of duplication.

Session is a server-side storage space maintained by the application server. When users connect to the server, the server will generate a unique session ID, which is used as an identifier to access the server-side session storage space. The session ID data is saved to the client and saved with cookie. When the user submits the page, the session ID will be submitted to the server to access the session data. This process does not need the intervention of developers. So once the cookie is disabled by the client, the session will also be invalid.

2. Cookies are not very secure. Others can analyze the local cookies and cheat them. Session should be used for security.

3. Setting the cookie time can make the cookie expire. But with session destory (), we will destroy the session.

4. The session will be saved on the server for a certain period of time. When access increases, it will occupy the performance of your server. In order to reduce the performance of your server, you should use cookies.

5. A single cookie can’t save more than 4K data. Many browsers limit a site to save up to 20 cookies( Session object has no limitation on the amount of data stored, in which more complex data types can be saved.)

be careful:

Session is easy to fail and user experience is poor;

Although cookies are not secure, they can be encrypted  ;

Cookies are also classified as permanent and temporary;

The browser has the function of forbidding cookies, but most users will not set it;

Be sure to set the expiration time, or the browser will disappear when it is closed;

For example:

Remember that the password function is to use a permanent cookie to write on the client computer. The next time you log in, you will automatically send additional cookie information to the server.

Application is global information, which is the information shared by all users. For example, it can record how many users have logged in to this website, and display the information to all users.

The biggest difference between the two lies in the life cycle. One is the life cycle from IE startup to IE shutdown (session disappears as soon as the browser page closes). The other is the life cycle set in advance, or the file permanently saved in the local( cookie)

Session information is stored in the server, but session ID is stored in the client cookie. Of course, PHP’s session storage methods are diversified, so that it can be tracked even if the cookie is disabled

Cookies are completely kept in the client, such as IE firebox. When the client forbids cookies, it can no longer be used

Recommended Today

Hot! Front and rear learning routes of GitHub target 144K

Hello, Sifu’s little friend. I’m silent Wang Er. Last week, while appreciating teacher Ruan Yifeng’s science and technology weekly, I found a powerful learning route, which has been marked with 144K on GitHub. It’s very popular. It covers not only the front-end and back-end learning routes, but also the operation and maintenance learning routes. As […]