Home > Web Front-end > HTML Tutorial > Detailed explanation of Cookie/Session mechanism_html/css_WEB-ITnose

Detailed explanation of Cookie/Session mechanism_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:49:47
Original
1294 people have browsed it

Session tracking is a commonly used technology in web programs, which is used to track a user's entire session. Commonly used session tracking technologies are Cookie and Session. Cookie determines the user's identity by recording information on the client side, and Session determines the user's identity by recording information on the server side.

This chapter will systematically describe the Cookie and Session mechanisms, and compare and explain when Cookie cannot be used and when Session cannot be used.

1.1 Cookie mechanism

In the program, session tracking is a very important thing. Theoretically, all request operations of one user should belong to the same session, while all request operations 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 A’s shopping cart. No matter when user A purchases it, it belongs to the same session and cannot be placed in user B’s or user C’s shopping cart. , which does not belong to the same session.

Web applications use the HTTP protocol to transmit data. HTTP protocol 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, user A purchases an item and puts it in the shopping cart. When the item is purchased again, the server cannot determine whether the purchase belongs to user A's session or user B's session. To track this session, a mechanism must be introduced.

Cookie is such a mechanism. It can make up for the stateless shortcomings of the HTTP protocol. Before Session appeared, basically all websites used cookies to track sessions.

1.1.1 What is Cookie

Cookie means "sweet cookie", which was proposed by the W3C organization and first developed by the Netscape community a mechanism. Currently, cookies have become a standard, and all mainstream browsers such as IE, Netscape, Firefox, Opera, etc. support cookies.

Since HTTP is a stateless protocol, the server has no way of knowing the identity of the client from the network connection alone. What to do? Just issue a pass to the clients, one for each person. No matter who visits, they must bring their own pass. This way the server can confirm the client's identity from the pass. This is how cookies work.

Cookie is actually a short piece of text information. The client requests the server. If the server needs to record the user 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 this cookie to identify the user's status. The server can also modify the contents of the cookie as needed.

It’s easy to check the cookies issued by a website. Just enter javascript:alert (document. cookie) in the browser address bar (you need an Internet connection to view it). The JavaScript script will pop up a dialog box to display the contents of all cookies issued by this website, as shown in Figure 1.1.

Figure 1.1 Cookie issued by Baidu website

The cookie that pops up in the dialog box shown in Figure 1.1 is the cookie of Baidu website. The first line of BAIDUID records the author's identity helloweenvsfei, 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 the browsers on most mobile phones) or if cookies are disabled, the cookie function will be invalid.

Different browsers use different methods to save cookies.

IE browser will save it as a text file in the "C:Documents and Settings Your Username Cookies" folder, and each text file saves one cookie.

1.1.2 Record the number of user visits

In Java, Cookie is encapsulated into the javax.servlet.http.Cookie class. Each cookie is an object of this Cookie class. The server operates client cookies by operating Cookie class objects. Obtain all Cookies submitted by the client through request.getCookie() (returned in the form of Cookie[] array), and set Cookie to the client through response.addCookie(Cookiecookie).

Cookie objects use key-value attribute pairs to save user status. 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 Cookies cannot cross domain names

Many websites use cookies. For example, Google will issue Cookie to the client, and Baidu will also issue Cookie to the client. Will the browser also carry cookies issued by Baidu when accessing Google? Or can Google modify the cookies issued by Baidu?

The answer is no. Cookies cannot cross domain names. According to the cookie specification, when a browser accesses Google, it will only carry Google's cookies and not Baidu's cookies. Google can only operate Google's cookies, but not Baidu's cookies.

Cookies are managed by the browser on the client side. The browser can ensure that Google will only operate Google's cookies and not Baidu's cookies, thereby ensuring user privacy and security. The browser determines whether a website can operate another website's cookie based on the domain name. The domain names of Google and Baidu are different, so Google cannot operate Baidu's cookies.

It should be noted that although the website images.google.com and the website www.google.com belong to Google, their domain names are different, and they cannot operate each other's cookies.

Note: After logging in to the website www.google.com, the user will find that the login information is still valid when visiting images.google.com, which is not possible with ordinary cookies. This is because Google has done special processing. Cookies will be treated similarly later in this chapter.

1.1.4 Unicode encoding: Saving Chinese

Chinese characters are different from English characters. Chinese characters are Unicode characters and occupy a large space in memory. 4 characters, while English is ASCII characters and only occupies 2 bytes in memory . When using Unicode characters in cookies, the Unicode characters need to be encoded, otherwise they will be garbled.

Tips: Chinese characters can only be saved in cookies. Generally, UTF-8 encoding can be used. It is not recommended to use Chinese encodings such as GBK because browsers may not support it, and JavaScript does not support GBK encoding.

1.1.5 BASE64 encoding: Save binary images

Cookie can not only use ASCII characters and Unicode characters, but also binary data. For example, digital certificates are used in cookies to provide security. Encoding is also required when working with binary data.

% Note: This program is only used to demonstrate that binary content can be stored in cookies, and is not practical. Since the browser will carry cookies every time it requests the server, the cookie content should not be too much, otherwise it will affect the speed. The content of cookies should be small but precise.

1.1.6 Set all attributes of Cookie

In addition to name and value, Cookie also has several other commonly used attributes. Each property corresponds to a getter method and a setter method. All properties of the Cookie class are shown in Table 1.1.

Table 1.1 Cookie common attributes

属  性  名

描    述

String name

该Cookie的名称。Cookie一旦创建,名称便不可更改

Object value

该Cookie的值。如果值为Unicode字符,需要为字符编码。如果值为二进制数据,则需要使用BASE64编码

int maxAge

该Cookie失效的时间,单位秒。如果为正数,则该Cookie在maxAge秒之后失效。如果为负数,该Cookie为临时Cookie,关闭浏览器即失效,浏览器也不会以任何形式保存该Cookie。如果为0,表示删除该Cookie。默认为?1

boolean secure

该Cookie是否仅被使用安全协议传输。安全协议。安全协议有HTTPS,SSL等,在网络上传输数据之前先将数据加密。默认为false

String path

该Cookie的使用路径。如果设置为“/sessionWeb/”,则只有contextPath为“/sessionWeb”的程序可以访问该Cookie。如果设置为“/”,则本域名下contextPath都可以访问该Cookie。注意最后一个字符必须为“/”

String domain

可以访问该Cookie的域名。如果设置为“.google.com”,则所有以“google.com”结尾的域名都可以访问该Cookie。注意第一个字符必须为“.”

String comment

该Cookie的用处说明。浏览器显示Cookie信息的时候显示该说明

int version

该Cookie使用的版本号。0表示遵循Netscape的Cookie规范,1表示遵循W3C的RFC 2109规范

Attribute Name
Description
String name The name of this 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, the character needs to be encoded. If the value is binary data, you need to use BASE64 encoding
int maxAge The expiration time of this cookie, in seconds. If positive, the cookie expires after maxAge seconds. If it is a negative number, the cookie is a temporary cookie and will become invalid when the browser is closed, and the browser will not save the cookie in any form. If it is 0, it means to delete the cookie. The default is ?1
boolean secure Whether this cookie is only used by secure protocols transmission. Security protocols. Security protocols include HTTPS, SSL, etc., which encrypt data before transmitting it on the network. The default is false
String path The path used by this cookie. If set to "/sessionWeb/", only programs whose contextPath is "/sessionWeb" can access the cookie. If set to "/", the cookie can be accessed by the contextPath under this domain name. Note that the last character must be "/"
String domain The domain name that can access the cookie . If set to ".google.com", all domain names ending with "google.com" can access this cookie. Note that the first character must be "."
String comment Description of the use of this cookie . The browser displays this description when displaying cookie information
int version The version used by this cookie Number. 0 means following Netscape's Cookie specification, 1 means following W3C's RFC 2109 specification

1.1.7 Cookie Validity Period

The maxAge of Cookie determines the validity period of Cookie, in seconds. In Cookie, the maxAge attribute is read and written through the getMaxAge() method and the setMaxAge(int maxAge) method.

If the maxAge attribute is a positive number, it means that the cookie will automatically expire after maxAge seconds. The browser will persist the cookie with a positive maxAge, that is, write it to the corresponding cookie file. Regardless of whether the customer closes the browser or the computer, as long as it is maxAge seconds ago, the cookie is still valid when logging into the website. The cookie information in the code below will be valid forever.

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

cookie.setMaxAge( Integer.MAX_VALUE); // Set the life cycle to MAX_VALUE

response.addCookie(cookie); 🎜>

If maxAge is a negative number, it means that the cookie is only valid within this browser window and the sub-windows opened by this window. The cookie will become invalid after closing the window. Cookies with a negative maxAge are temporary cookies and will not be persisted or written to the cookie file. Cookie information is stored in the browser's memory, so the cookie disappears when you close the browser. The default maxAge value of Cookie is ?1.

If maxAge is 0, it means the cookie is deleted. The cookie mechanism does not provide a method to delete cookies, so the effect of deleting cookies is achieved by setting the cookie to expire immediately. Invalid cookies will be deleted from the cookie file or memory by the browser,

For example:

Cookie cookie = new Cookie("username","helloeenvsfei"); // Create a new Cookie

cookie.setMaxAge(0);

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

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

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

1.1.8 Cookie modification and deletion

Cookie does not provide modification or deletion operations. If you want to modify a cookie, you only need to create a new cookie with the same name and add it to the response to overwrite the original cookie.

If you want to delete a cookie, you only need to create a new cookie with the same name, set maxAge to 0, and add it to the response to overwrite the original cookie. Note that it is 0 and not a negative number. Negative numbers represent other meanings. Readers can verify and set different attributes through the program in the above example.

Note: When modifying or deleting cookies, all attributes of the newly created cookie, except value and maxAge, such as name, path, domain, etc., must be exactly the same as the original cookie. Otherwise, the browser will treat it as two different cookies and will not overwrite them, causing modification and deletion to fail.

1.1.9 Cookie domain name

Cookies cannot cross domain names. Cookies issued by the domain name www.google.com will not be submitted to the domain name www.baidu.com. This is determined by the privacy security mechanism of Cookie. The privacy security mechanism can prevent websites from illegally obtaining cookies from other websites.

Under normal circumstances, two second-level domain names under the same first-level domain name, such as www.helloweenvsfei.com and images.helloweenvsfei.com, cannot use cookies interchangeably because the domain names of the two are not strictly the same. If you want all second-level domain names under the helloweenvsfei.com name to be able to use this cookie, you need to set the domain parameter of the cookie, for example:

Cookie cookie = new Cookie("time","20080808"); // Create a new Cookie cookie.setDomain(".helloweenvsfei.com"); // Set the domain name

cookie.setPath("/"); // Set the path

cookie .setMaxAge (Integer.MAX_VALUE);

Readers can modify the hosts file under C:WINDOWSsystem32driversetc on the local machine to configure multiple temporary domain names, and then use the setCookie.jsp program to set the cross-domain cookie verification domain attribute.

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 cookies, you can generate two cookies, with the domain attribute being two domain names respectively, and output them to the client.

1.1.10 Cookie path

The domain attribute determines the domain name that runs to access the cookie, and the path attribute determines the path allowed to access the cookie (ContextPath ). For example, if you only allow programs under /sessionWeb/ to use cookies, you can write:

Cookie cookie = new Cookie("time","20080808"); // Create a new Cookie

cookie .setPath("/session/"); // Set path

response.addCookie(cookie); 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 it belongs to. For example, /session/test/a.jsp cannot obtain the cookie with the path /session/abc/. Be careful when using it.

1.1.11 Cookie security properties

The HTTP protocol is not only stateless, but also insecure. Data using the HTTP protocol is transmitted directly on the network without any encryption, and may be intercepted. Using the HTTP protocol to transmit very confidential content is a hidden danger. If you do not want cookies to be transmitted in non-secure protocols such as HTTP, you can set the secure attribute of the cookie to true. Browsers only transmit such cookies over secure protocols such as HTTPS and SSL. The following code sets the secure attribute to true:

Cookie cookie = new Cookie("time", "20080808"); // Create a new Cookie

Cookie.setSecure (TRUE); // Set security attributes

Response.addcookie (cookie); // Output to the client

>

Tip: The secure attribute cannot encrypt the cookie content, so it cannot guarantee absolute security. If high security is required, you need to encrypt and decrypt the cookie content in the program to prevent leakage.

1.1.12 JavaScript operation cookie

Cookie is saved on the browser side, so the browser There are prerequisites for operating cookies. Browsers can use script programs such as JavaScript or VBScript to operate cookies. Here we take JavaScript as an example to introduce commonly used Cookie operations. For example, the following code will output all cookies on this page.

<script>document.write(document.cookie);</script>

Because JavaScript can read and write cookies arbitrarily, some bad guys want to use JavaScript programs to spy on users Cookies on other websites. But this is in vain. The W3C organization has long been aware of the security risks caused by JavaScript's reading and writing of cookies and has taken precautions. W3C standard browsers will prevent JavaScript from reading and writing any cookies that do not belong to their own website. In other words, website A's JavaScript program reading and writing website B's cookies will have no results.

1.1.13 Case: Permanent login

If the user is surfing the Internet on his own computer at home, he can be remembered when logging in Login information, you don’t need to log in again the next time you visit, just visit directly. The implementation method is to save login information such as account number, password, etc. in a cookie, and control the validity period of the cookie. Then verify the login information in the cookie the next time you visit.

There are many options for saving login information. The most direct thing is to save the username and password in the cookie, and check the username and password in the cookie the next time you visit, and compare it with the database. This is a more dangerous choice. Generally, passwords and other important information are not saved in cookies

.

Another solution is to encrypt the password and save it in a cookie, then decrypt it and compare it with the database during the next visit

. This solution is slightly safer. If you don't want to save the password, you can also save the login timestamp in Cookie and the database, and then only verify the user name and login timestamp.

These schemes all need to query the database when verifying the account.

This example will use another solution, which only queries the database once when logging in, and will no longer query the database when accessing to verify login information in the future. The implementation method is to encrypt the account according to certain rules and save it together with the account in the cookie. The next time you visit, you only need to determine 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 key are encrypted using the MD1 algorithm and then saved in a cookie named ssid. During verification, verify whether the encrypted account number and key in the Cookie are equal to the SSID in the Cookie. The relevant code is as follows:

Code 1.8 loginCookie.jsp

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

& Lt;%! // JSP method

Private Static Final String key = ": cookie@hellloweenvsfei.com";

// Key

Public Final String Calcmd1 ( Stringss) { // MD1 encryption algorithm

  String s = ss==null ?"" : ss; '1', '2', '3', '4', '1', '6', '7', '8', '9',

'a', 'b', 'c' , 'd', 'e', ​​'f' }; // Dictionary

try {

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

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

mdTemp.update(strTemp); byte[] md =mdTemp.digest( ); * 2];                                                                                                      >

int k =0; // Loop output

byte byte0 =md[i] ;

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

           return newString(str);                                                                                                                                                                          >% >

<%

request.setCharacterEncoding("UTF-8"); // Set request encoding

response.setCharacterEncoding("UTF-8"); // Set response encoding

String action =request.getParameter("action"); // Get action parameters

if ("login" .equals (action) {// If you are login action

String account = Request.getparameter ("Account");
// Get the account parameter

String password =request.getParameter("password");
int timeout = newInteger( request.getParameter("timeout"));

                                                                                 timeout parameter


                                                                                                                                                                                                                   Cookie("account", account);

                                                                          Period

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

ssidCookie.setMaxAge(timeout); countCookie);                     // Output to the client


           response.addCookie(ssidCookie);                                                            ’' The browser caches the page content

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

currentTimeMillis());

return; >

elseif("logout".equals(action)){ // If it is a logout action

CookieaccountCookie = new Cookie("account", "");

// Create a new cookie, the content is empty sid" , ""); // Create a new cookie with empty content

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

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

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

//Re-request this page, with a timestamp in the parameter, prohibiting the browser from caching the page content

response.sendRedirect(request.getRequestURI() "?" System.
currentTimeMillis()) ;

return;

}

boolean login = false; //Account

String ssid = null; // SSID identifier

if(request.getCookies() !=null){ for(Cookie cookie :request.getCookies()){ // Traverse Cookies

                                                                               account

account = cookie.getValue(); // Save account content

if(cookie.getName().equals("ssid")) // If it is SSID

ssid = cookie.getValue ();                                                                                                       Empty

        login =ssid.equals(calcMD1(account KEY));                                                                                                      >%> ;

            <%= login ? "Welcome back " : "Please log in first" %>

                                                                                                                                        "   

                                                                                              else {%>

                                                                                                                                                             

& lt; tr & lt; & lt; td & gt; account: & lt;/td & gt;

& lt; td & lt; input type = "text" name = "account" = "wid" Th:

                                                                                                     ;/td>

                                                  ;td>

                                                   

                                                                                                                .           checked> Close browser It will be invalid
                                                                                                                                using                                                     ‐ ‐ ‐ ‐                                                                              Valid
Permanently valid


                                                                record" class= 
                                                                              >      

                                                                                                                                                                                                                                  You can choose the validity period of the login information when logging in. It is valid within 30 days or permanently. This is achieved by setting the age attribute of the cookie, and pay attention to the code. The running effect is shown in Figure 1.7.

Figure 1.7 Permanent login

Tip: The most important part of this encryption mechanism is the algorithm and key. Due to the irreversibility of the MD1 algorithm, even if the user knows the account number and the encrypted string, it is impossible to decrypt and obtain the key. Therefore, as long as the key and algorithm are kept, the mechanism is safe.

1.2 Session Mechanism

In addition to using Cookies, Sessions are often used in Web applications to record client status.

Session is a mechanism used by the server to record the status of the client

. It is simpler to use than Cookie. It also

increases the storage pressure of the server

accordingly.

1.2.1 What is Session

Session is another mechanism for recording client status. The difference is that Cookie is saved in the client browser, while Session is saved on the server. When the client browser accesses the server, the server records the client information on the server in some form. This is Session. When the client browser visits again, it only needs to find the status of the customer from the Session.

If the Cookie mechanism determines the customer's identity by checking the "passport" on the customer, then the Session mechanism confirms the customer's identity by checking the "customer details" on the server. Session is equivalent to a customer file created by the program on the server. When a customer comes to visit, he only needs to query the customer file table.

1.2.2 Implementing user login

The class corresponding to Session is javax.servlet.http.HttpSession class. Each visitor corresponds to a Session object, and all the customer's status information is stored in this Session object.

The Session object is created when the client first requests the server . Session is also a key-value attribute pair. It reads and writes customer status information through the getAttribute(Stringkey) and setAttribute(String key, Objectvalue) methods. In the Servlet, obtain the client's Session through the request.getSession() method,

For example:

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

session .setAttribute("loginTime", new Date()); // Set attributes in Session

out.println("Login time is: " (Date)session.getAttribute(" loginTime")); // Get the Session attribute

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 first create the Session and then return the Session.

Request must be used in Servlet to programmatically obtain the HttpSession object, and the Session hidden object is built into JSP and can be used directly. If <%@page session="false" %> is declared, the Session hidden object is not available. The following example uses Session to record customer account information.

The source code is as follows:

Code 1.9 session.jsp

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

<%!

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

%>

<%

response.setCharacterEncoding("UTF-8"); // Set request encoding

Person[] persons =

{ >          // Basic data, save the information of three people

                                                                                                                                     >

new Person("Hello Kitty","hellokitty", 23, dateFormat.parse

("1984-02-21")),

new Person("Garfield", "garfield_pass ",23, dateFormat.parse

        ("1994-09-12")),
                                                              Displayed message

 

if(request.getMethod().equals("POST"))

                                                                                🎜>

for(Person person:persons)

{ Correct {

// Login is successful, set the user's information and save the login time to the session

Session.Setattribute ("Person", Person); // > session.setAttribute("loginTime", new Date()); // Save login time

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

return;

}

}                                                                                                                                                "; // Login failed

}

%>

// ... The HTML code is a FORM form, the code is omitted, please see the accompanying CD

The login interface verifies the user's login information. If the login is correct, the user information and login time are saved in the Session, and then go to the welcome page welcome.jsp. Welcome.jsp obtains information from Session and displays user information.

welcome.jsp code is as follows:

Code 1.10 welcome.jsp

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

<%!

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

%>

<%

Person person =(Person)session.getAttribute("person"); // Get the logged in person

Date loginTime =(Date)session.getAttribute(" loginTime");                                                                       < ;tr>Your name:

                                                                    ;/tr>

                                                                   < ;

                                                                                                    lt;td><%= person.getAge ()%>

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

                                                >

The program running effect is shown in Figure 1.8.

Figure 1.8 Using Session to record user information

Note that Person class objects and Date class objects are directly saved in Session in the program, which is more convenient to use than Cookie.

When multiple clients execute the program, the server will save the Sessions of multiple clients. When acquiring a Session, there is no need to declare whose Session it is to acquire.

The Session mechanism determines that the current client will only obtain his own Session and not other people’s Sessions. The sessions of each client are also independent of each other and invisible to each other

.

Tips

: Session is more convenient to use than Cookie, but too many Sessions stored in the server memory will put pressure on the server.

1.2.3 Session life cycle

Session is saved on the server side.

In order to obtain higher access speed, servers generally store Sessions in memory. Each user will have an independent Session. If the Session content is too complex, memory overflow may occur 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 a Session will only be created when accessing JSP, Servlet and other programs. Only accessing static resources such as HTML and IMAGE will not create a Session. If a Session has not been generated yet, you can also use request.getSession(true) to force a Session to be generated.

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 accesses the server, regardless of whether the session is read or written, the server considers the user's session to be "active".

1.2.4 Session Validity Period

As more and more users access the server, there will be more and more Sessions. . To prevent memory overflow, the server will delete Sessions that have not been active for a long time from memory. This time is the Session timeout time. If the server is not accessed after the timeout period, the Session will automatically expire.

Session’s timeout is the maxInactiveInterval attribute, which can be obtained through the corresponding getMaxInactiveInterval() and modified through setMaxInactiveInterval(longinterval).

Session timeout can also be modified in web.xml. In addition, the Session can be invalidated by calling the Session's invalidate() method.

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

tr>

方  法  名

描    述

void setAttribute(String attribute, Object value)

设置Session属性。value参数可以为任何Java Object。通常为Java Bean。value信息不宜过大

String getAttribute(String attribute)

返回Session属性

Enumeration getAttributeNames()

返回Session中存在的属性名

void removeAttribute(String attribute)

移除Session属性

String getId()

返回Session的ID。该ID由服务器自动创建,不会重复

long getCreationTime()

返回Session的创建日期。返回类型为long,常被转化为Date类型,例如:Date createTime = new Date(session.get CreationTime())

long getLastAccessedTime()

返回Session的最后活跃时间。返回类型为long

int getMaxInactiveInterval()

返回Session的超时时间。单位为秒。超过该时间没有访问,服务器认为该Session失效

void setMaxInactiveInterval(int second)

设置Session的超时时间。单位为秒

void putValue(String attribute, Object value)

不推荐的方法。已经被setAttribute(String attribute, Object Value)替代

Object getValue(String attribute)

不被推荐的方法。已经被getAttribute(String attr)替代

boolean isNew()

返回该Session是否是新创建的

void invalidate()

使该Session失效

Method Name
Description td>
void setAttribute(String attribute, Object value) Set Session attribute. The value parameter can be any Java Object. Usually a Java Bean. The value information should not be too large
String getAttribute(String attribute) Return Session attribute
Enumeration getAttributeNames() Return the attribute names existing in the Session
void removeAttribute(String attribute) Remove Session attribute
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 Session Creation date. 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 there is no access after this time, the server considers the Session to be invalid
void setMaxInactiveInterval(int second) Set the Session timeout. The unit is seconds
void putValue(String attribute, Object value) Deprecated method. Has been replaced by setAttribute(String attribute, Object Value)
Object getValue(String attribute) Not a recommended method. Has been replaced by getAttribute(String attr)
boolean isNew() Returns whether the Session is Newly created
void invalidate() Invalidate the Session

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

60

Note: The unit of the parameter is minutes, while the unit of setMaxInactiveInterval(int s) is seconds.

1.2.6 Session requirements for browsers

Although the Session is saved on the server, it is transparent to the client and it operates normally Client browser support is still required. This is because Session needs to use Cookie as an identification mark. The HTTP protocol is stateless, and the Session cannot determine whether it is the same client based on the HTTP connection. Therefore, the server sends a Cookie named JSESSIONID to the client browser, and its value is the ID of the Session (that is, HttpSession.getId() return value). Session uses this cookie to identify whether it is the same user.

This cookie is automatically generated by the server. Its maxAge attribute is generally ?1, which means it is only valid within the current browser and is not shared between browser windows. It will become invalid when the browser is closed.

So when two browser windows on the same machine access the server, two different Sessions will be generated. However, new windows opened by links, scripts, etc. within the browser window (that is, windows that are not opened by double-clicking the desktop browser icon, etc.) are excluded. This type of child window will share the cookie of the parent window and therefore share a Session.

Note: A new browser window will generate a new Session, except for child windows. Child windows will share the Session of the parent window. For example, when you right-click on a link and select "Open in new window" from the pop-up shortcut menu, the child window can access the Session of the parent window.

What if the client browser disables the Cookie function or does not support Cookies? For example, the vast majority of 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 for clients that do not support cookies. The principle of URL address rewriting is to rewrite the user's Session ID information into the URL address. The server can parse the rewritten URL to obtain the Session ID. In this way, even if the client does not support cookies, Session can be used to record user status. The HttpServletResponse class provides encodeURL (Stringurl) to implement URL address rewriting, for example:

">
Homepage

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 user Session id will be rewritten into the URL. The rewritten output may look like this:

1&wd=Java"> Homepage

That is, the string ";jsessionid=XXX" is added after the file name and in front of the URL parameters. Where XXX is the ID of the Session. An analysis shows that the added jsessionid string will neither affect the requested file name nor the submitted address bar parameters. When the user clicks this link, the Session ID will be submitted to the server through the URL, and the server will obtain the Session ID by parsing the URL address.

If it is a page redirection (Redirection), the URL address rewriting can be written like this:

<%

if("administrator".equals(userName))

{

response.sendRedirect(response.encodeRedirectURL("administrator.jsp"));

return;

}

% >

The effect is the same as response.encodeURL(String url): if the client supports Cookie, the original URL address is generated. If Cookie is not supported, the rewritten address with the jsessionid string is returned. .

For WAP programs, since most mobile browsers do not support cookies, WAP programs will use URL address rewriting to track user sessions. For example, UFIDA Group’s mobile shopping mall.

Note: TOMCAT determines whether the client browser supports cookies based on whether the request contains cookies. Although the client may support cookies, since no cookies will be carried in the first request (because there are no cookies to carry), the rewritten URL address will still contain jsessionid. When accessing for the second time, the server has already written the cookie in the browser, so the URL address after rewriting will not contain jsessionid.

1.2.8 It is forbidden to use cookies in Session

Since most client browsers on WAP do not support cookies, simply prohibit the use of cookies in Session and use URL address rewriting in a unified way. Better. The Java Web specification supports disabling cookies through configuration. Here is an example of how to disable the use of cookies through configuration.

Open the META-INF folder in the WebRoot directory of the project sessionWeb (same level as the WEB-INF folder, create it if it does not exist), open context.xml (create it if it does not exist), and edit the content as follows:

Code 1.11 /META-INF/context.xml

Or modify Tomcat's global conf/context.xml, the modification content is as follows :

Code 1.12 context.xml

TOMCAT will not be automatically generated after deployment Cookie named JSESSIONID, Session will not use the cookie as the identification mark, but only the rewritten URL address as the identification mark.

Note: This configuration only prohibits Session from using Cookie as an identification mark, and does not prevent other Cookies from reading and writing. In other words, the server will not automatically maintain the cookie named JSESSIONID, but other cookies can still be read and written in the program.

http://blog.csdn.net/fangaoxin/article/details/6952954

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template