Session tracking is a commonly used technology in Web programs, used totrack the 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,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 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 sessionfrom 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 wasproposed by the W3C organizationand 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.
Because HTTP is a stateless protocol, the server has no way of knowing the identity of the client from the network connection alone. How to do it? Justissue 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.
Checking the cookies issued by a website is easy. Just enterjavascript: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
As shown in the pop-up dialog box in Figure 1.1 Cookie for 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 disables cookies, 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 the client Cookie by operating Cookie class objects. Obtain all Cookiessubmitted by the client throughrequest.getCookie() (returned in the form of Cookie[] array),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 cookies to the client, and Baidu will also issue cookies 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 negative.Cookies cannot cross domain names.According to the cookie specification, the browser will only carry Google's cookies when accessing Google, but 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 the cookie of another website 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 the user logs in to the website www.google.com, he or she 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: Save Chinese
Chinese and English characters are different,Chinese belongs to Unicode characters, in It occupies 4 characters in the memory, while English is ASCII characters and only occupies 2 bytes in the memory. When using Unicode characters in cookies, the Unicode characters need to be encoded, otherwise they will be garbled.
Tips: Only Chinese characters saved in cookies can be encoded. 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: saving 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 properties of Cookie
In addition to name and value, Cookie also has several other commonly used properties. 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
1.1.7 Cookie validity period
The maxAge of Cookie determines the validity period of Cookie, in seconds (Second ). 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 in to 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); // Output to the client
#The Cookie operation method provided by the response object has only one add operation add(Cookie cookie).
Note: When reading 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 the browser 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 a cookie, all attributes of the newly created cookie, except value and maxAge, such as name, path, domain, etc., must be completely identical to the original cookie. Same. 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 interactively 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"); .setMaxAge (Integer.MAX_VALUE);
Readers can modify the hosts file under C:\WINDOWS\system32\drivers\etc 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 domain name that is allowed to access the Cookie path(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); // Output to the client
Set "/" and allow all paths 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 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 attributes
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 will 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
Tip: The secure attribute cannot encrypt the cookie content, so it cannot guarantee absolute security. If high security is required,the cookie content needs to be encrypted and decrypted in the program to prevent leakage.
1.1.12 JavaScript operation cookie
Cookie is saved on the browser side. The browser therefore has 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.
Because JavaScript can read and write cookies arbitrarily, some good people 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 reading and writing 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 or her home computer, he/she can remember it when logging in. Keep his login information. You don’t need to log in again when you visit next time. You can just access directly. The implementation method is tosave login information such as account number, password, etc. in Cookie, and control the validity period of Cookie, and then verify the login information in 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 isa more dangerous choice. Generally, passwords and other important information are not saved in Cookies.
AlsoOne solution is to encrypt the password and save it in a cookie, then decrypt it and compare it with the databaseon 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 must query the database when verifying accounts.
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 toencrypt 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 the 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" %>
<%! final String KEY =":cookie@helloweenvsfei.com";
char hexDigits[] = { '0','1', '2', '3', '4', '1 ', '6', '7', '8', '9',
## try {
byte[] strTemp =s.getBytes(); // Get bytes
MessageDigestmdTemp = MessageDigest.getInstance("MD1"); // Get MD1
*
byte byte0 =md[i];
str[k++] =hexDigits[byte0 > ;>> 4 & 0xf];
Post string
} catch (Exception e){return null; }
}
%>
<%
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 it is a login action
String account =request.getParameter("account");
int timeout = newInteger(request.getParameter("timeout"));
String ssid =calcMD1(account + KEY); // Use MD1 to encrypt the account and key and save them. accountCookie.setMaxAge (timeout);
use to rerequest this page, with a timestamp in the parameters, and prohibit the browser from caching the content of the page. off out out off out out out right back ‐ out out out out out out out out out back out out mp out out out out out out out out out out out Out out out out out out together together - , - i - and System.
CookieaccountCookie = new Cookie("account", " use to cookieaccountCookie = new("account", " " ”); (0); // Set the validity period For 0, delete
## SSIDCOOKIE.Setmaxage (0) ; ;
Currentttimemlymis ( ));
return;
# SSID = cookie.getValue (); // Save ssid content
#}
}
if(account != null && ssid !=null){ // If neither account nor SSID is empty
login =ssid.equals(calcMD1(account + Key);
#%& gt;
& lt;! Doctype html public "- //W3C//DTD HTML 4.01Transitional//EN">
"${ pageContext.request.requestURI }?action=logout">
method="post">
"table>
Attribute Name |
Description |
String name |
The name of this cookie. Once a cookie is created, its name cannot be changed |
Object value |
The value of this 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 cookie expiration time, 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. Default is –1 |
boolean secure | Whether this cookie is only transmitted using secure protocols. Security Protocol. 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. When the browser displays cookie information, it displays this description |
int version | The version number used by the cookie. 0 means following Netscape's Cookie specification, 1 means following W3C's RFC 2109 specification |
账号: | |
密码: |
|
有效期: |
name="timeout" value="<%= 30*24*60*60 %>"> 30天 内有效 "<%= Integer.MAX_VALUE %>"> 永久有效 |
"button"> |
Tips: The most important parts of this encryption mechanism are the algorithm and the 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 client status. It is simpler to use than Cookie, and accordinglyincreases the storage pressure on the server.
1.2.1 What is Session
Session is another mechanism for recording client status. The difference is that Cookie is stored in the client browser. The 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 theCookie 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 Implement user login
The class corresponding to Session is the 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 createdwhen the client requests the server for the first time. 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 Sessionout.println("The 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 obtain the HttpSession object programmatically, 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("Liu Jinghua","password1", 34, dateFormat.parse
("1982-01-01")) ,
new Person("Hello Kitty","hellokitty", 23, dateFormat.parse
new Person("Garfield", "garfield_pass",23, dateFormat.parse
("1994-09-12")),
};
String message = "";
// If it is POST login # for (Person Person: Persons)
{
# // Traversing the basic data, verification Account number, password
’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ away’s’ out out out out out out out out out out out out out outs outs's (request.getParameter("password")))
. "person", person); . Redirect(request .getContextPath() + "/welcome.jsp");
# ;
// .. . The HTML code is a FORM form. The code is omitted. Please see the accompanying CD
## login interface to verify user login information. If If the login is correct, save the user information and login time into 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"%>
Date loginTime =(Date)session.getAttribute("loginTime"); // Get the login time
%>
// ...Part of the HTML code is omitted
Your name:>
gt; <%= loginTime%>
## you 's birthday: ;
;
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 its 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 are stored in the server memory, which will put pressure on the server.
##1.2.3 Session life cycle
##Session Saved on the server side.In order to obtain higher access speed, the server generally places the Session 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 createdwhen 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.
SAfter 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".
As more and more users access the server, the Session will also become longer and longer. Come more and more.
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 time is the maxInactiveInterval attribute, which can be obtained through the corresponding getMaxInactiveInterval() and modified through setMaxInactiveInterval(longinterval).
Session’s timeout can also be modified in web.xml. In addition, the Session can be invalidated by calling the Session's invalidate() method.
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
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:
Note: The unit of the
1.2.6 Session requirements for browsers
Although Session is saved on the server and is transparent to the client, it Normal operation still requires support from the client browser. 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() The 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 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 should I do 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:
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's Session ID will be rewritten into the URL. The rewritten output may be like this:
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")); >
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.
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.
1.2.8 Disable the use of cookies in Session
Since most client browsers on WAP do not support cookies, simply disable the use of Session Cookie, it would be better to use URL address rewriting uniformly. The Java Web specification supports disabling cookies through configuration. The following 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
The above is the detailed content of Introduction to Cookie/Session Mechanism. For more information, please follow other related articles on the PHP Chinese website!