The cookie mechanism of the first knowledge JSP

Source: Internet
Author: User
Tags set cookie

The stateless nature of the HTTP protocol

When we are developing Web applications, we use the HTTP protocol to transfer data, but this HTTP protocol has a congenital deficiency, that is, stateless, it cannot save the state of the user management. the so-called stateless means that when the browser sends a request to the server, the server responds to the client request, but when the same browser sends a request to the server again, the server does not know that it is just the browser. Simply put, the server is not going to remember you. So it's called a stateless protocol.

Because the HTTP protocol is a stateless protocol. once the data has been exchanged, the client-to-server connection is closed, and exchanging the data again requires establishing a new connection . This means that the server is unable to track the session from the connection. However, to track this session, you must introduce a mechanism.


Cookies are such a mechanism. It can compensate for the lack of HTTP protocol stateless. Before the session, basically all websites use cookies to track conversations.

Session tracking is a common technique used in Web programs to track a user's entire session. Common session tracking techniques are cookies and sessions. The cookie determines the user's identity by logging information on the client, and the session determines the user's identity by logging information on the server side.

Cookie mechanism

What is a cookie?

Cookie: The Chinese name is "Cookie", which is a series of text messages that the Web server holds on the client.

Typical application one: Determine whether the registered user has logged on to the website

Typical application two: "Shopping cart" processing

A typical video site usually records the video records that the user has seen (browsing history)

The Web login module also uses cookie technology to record user names and passwords for automatic user login

The role of Cookies

1, the tracking of specific objects

2. Save users ' browsing history and habits

3, simplified login (realize user automatic login)

Security risk: Easy disclosure of user information privacy

Creating and using cookies in JSP

1. Create a Cookie Object

Cookie Newcookie = Newcookie (stringkey,string value);

2. Write Cookie Object

Response.addcookie (Newcookie);

3. Read the Cookie Object

cookie[] cookies = request.getcookies ();

Common methods

Method Name Description

void setmaxage (int expiry)  //Set the cookie's validity period void SetValue (string value)//After the cookie is created, assign a value to the cookie String getName ()  //Gets the name of the cookie string getValue ()  //Gets the value of the cookie int getmaxage ()  //Gets the effective time of the cookie, in seconds

Session mechanism


In addition to using the Cookie,web application, the session is often used to record client status. Session is a server-side use of the mechanism to record client status, the use of more than a cookie is simpler, the corresponding increase the storage pressure of the server.

What is a session?

The session is another mechanism for recording the state of a customer, but the cookie is stored in the client browser and the session is stored on the server. When the client browser accesses the server, the server logs the client information to the server in some way. This is the session. When the client browser accesses it again, it only needs to find the customer's status from that session.

The class corresponding to the session is the Javax.servlet.http.HttpSession class. Each caller corresponds to a Session object, and all of the client's status information is stored in the session object. The session object is created the first time the client requests the server. The session is also a Key-value property pair that reads and writes client state information through the getattribute (Stringkey) and setattribute (Stringkey,objectvalue) methods. The servlet obtains the client's session through the Request.getsession () method,

For example:

HttpSession session = Request.getsession ();//Get Session Object Session.setattribute ("Logintime", Newdate ()); Set the properties in the session


Common methods of Session

The session includes a variety of methods that are much more convenient to use than cookies. The usual methods for session are as follows.

Common methods of HttpSession

Method name Description void SetAttribute (String attribute, Objectvalue) Set session Property. The value parameter can be any Java Object. Typically a Java Bean. The value information should not be too large string getattribute (string attribute) to return the Session property enumeration Getattributenames () returns the attribute name void that exists in the session RemoveAttribute (string attribute) removes the session property string GetId () returns the ID of the session. The ID is automatically created by the server and does not repeat long getcreationtime () to return the session's creation date. The return type is long and is often converted to a date type, for example: Datecreatetime = new Date (Session.get creationtime ()) long Getlastaccessedtime () Returns the last active time of the session. The return type is long int getmaxinactiveinterval () returns the time-out period for the session. Unit is seconds. After the time has not been accessed, the server considers the session to fail void Setmaxinactiveinterval (int second) to set the session timeout time. The unit is a second void Putvalue (String attribute, Objectvalue) method that is not recommended. The setattribute (string attribute, Object Value) has been substituted for the deprecated method of object GetValue (String attribute). A getattribute (stringattr) has been substituted for the Boolean isnew () to return whether the session is a newly created void invalidate () invalidates the session The default time-out for the session in Tomcat is 20 minutes. The time-out is modified by Setmaxinactiveinterval (Intseconds). can modify Web. Xml to change SessThe default time-out for Ion. For example, modified to 60 Minutes: <session-config><session-timeout>60</session-timeout><!--units: minutes--></ Session-config> Note that the:<session-timeout> parameter is in minutes, and Setmaxinactiveinterval (INTs) is seconds.

Session vs. Cookie:

Session                                                                      Cookie saves user information on the server side (stored in memory on the service side) saves                 the user information (in the form of a text file) on the client. The object type                                      is saved in the session. The cookie holds the data that is stored by the string type with the end of the session, and the                                 cookie can be saved for a long time on the client to save important information (high security information) to                             save unimportant user information (browsing history, access habits)


What the session and cookie have in common:

1, is a machine to save the user state

2, will expire, there is a period of time limit


The following cookie mechanism is used to make a very simple small example of saving the user's login status, so as to learn how to use the cookie mechanism in the JSP to save the user state. The example is very simple, just for yourself to understand better. A good memory is better than a rotten keyboard ....



1. login.jsp Login Page


<% @page import= "java.net.URLDecoder"%><%@ page language= "java" import= "java.util.*" contenttype= "text/html ; Charset=utf-8 "%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >


2. DOLOGIN.JSP Processing business logic


<% @page import= "java.net.URLEncoder"%><%@ page language= "java" import= "java.util.*" contenttype= "text/html ; Charset=utf-8 "%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

3. User.jsp View information


<% @page import= "java.net.URLDecoder"%><%@ page language= "java" import= "java.util.*" contenttype= "text/html ; Charset=utf-8 "%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >


If it is in Chinese, it needs to be urlencoder for encoding, and then the corresponding decoding operation is done with Urldecoder when it is taken.

Use Urlencoder () to encode to prevent Chinese garbled username = Urlencoder.encode (username, "Utf-8");p assword = urlencoder.encode (password, " Utf-8 ");


Request.setcharacterencoding ("Utf-8"); username = Urldecoder.decode (Cookie.getvalue (), "utf-8");


If you do not do the appropriate processing, the following error is reported:












today is only a preliminary understanding of the mechanism of cookies, but also a first knowledge of cookies, have heard of, but have not known how to use, the Internet said that cookies are not safe, the general project rarely use cookies, Here is also a simple understanding of the next cookie and session of the two mechanisms in the conceptual differences, as well as some usage of cookies, how to use in JSP, and the specific principle and implementation mechanism has not been deeply researched, practical application may be more complex, uh. Learn slowly later! Come on! Make a little progress every day, and soon you will see your own growth!

The cookie mechanism of the first knowledge JSP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.