Javaweb study note Five-session technology Cookie&session

Source: Internet
Author: User
Tags set cookie

What is session technology? For example, the website's shopping system, where will users store the product information they purchase? Because the HTTP protocol is stateless, which means that each client accesses a server-side resource, the server does not know who the client is, and therefore requires session technology to identify the state of the client. Session technology is to help the server remember the client state (differentiate the client).

from opening a browser to access a site, the entire process of closing the browser becomes a session. Session technology is the recording of the state and data of the client in this session. session technology is divided into cookie and session:

Cookies: The data is stored locally on the client, reducing the pressure on the server side of storage, security is not good, the client can clear the cookie.

Session: Store data on the server side, the security is relatively good, increase the pressure of the server.

Cookie Technology

Cookie technology is the technology that stores the user's data to the client, and we learn in two ways:

server-side sends a cookie to the client

1. Create a cookie: Cookie cookie = new cookie (String cookiename,string cookievalue) , for example: Cookie cookie = C4>new Cookies ("username", "Zhangsan");

The cookie is then sent to the client in the form of a response header. Note that Chinese is not stored in cookies.

2, set the cookie persistence time on the client: cookie.setmaxage (int seconds),---time seconds , Note that if you do not set the persistence time, Cookies are stored in the browser's memory, the browser shuts down cookie information destruction (session-level cookies), and if the persistence time is set, the cookie information is persisted to the browser's disk file.

For example: cookie.setmaxage (10*60) , set cookie information to be stored in the browser's disk file for 10 minutes, the outdated browser automatically deletes the cookie information.

3. Set the carrying path of the cookie: cookie.setpath (String path) , and Note that if you do not set the carry path, the cookie information will be accessed The path where the Web resource is located carries cookie information.

Example: cookie.setpath ("/web16") , which represents any resource in the Access WEB16 app that carries a cookie. Cookie.setpath ("/web16/cookieservlet"); , which represents access to Cookieservlet in WEB16 to carry cookie information.

4. Send a cookie to the client: Response.addcookie (Cookie cookie);

5, delete the client's cookie: If you want to delete the client's stored cookie information, then use the same name with the same path of persistent time of 0 cookie to overwrite it

// set the maximum effective time for a cookie // cookie.setmaxage (60*60); // set to 1, which is equivalent to the default time, and the browser shuts down. // cookie.setmaxage ( -1); // the valid time to mark a cookie is 0. Sent to the browser disappears. // with a valid time of 0, we can do a cookie removal operation. // because the same path, the same cookie cannot exist (the same key). // we can set the effective time to 0 by overriding the method. Delete Cookies // cookie.setmaxage (0);

Send a cookie Complete code example is as follows:

//1. Create a Cookie objectCookie cookie =NewCookie ("name", "Zhangsan");//1.1 Set persistent time for cookies----the time that cookie information was saved on the hard diskCookie.setmaxage (10*60);//10 min----time set to 0 means delete the cookie//1.2 Set the path to carry for the cookie//Cookie.setpath ("/web16/sendcookie");//only carry this cookie when accessing Sendcookie resourcesCookie.setpath ("/web16");//carry this cookie when accessing any resource under WEB16//Cookie.setpath ("/");//all resources under the Access server carry this cookie//2. Send the information stored in the cookie to the client---headerResponse.addcookie (cookie);
how the server accepts cookies that are carried by the client

Cookie information is sent to the server in the form of a request header:

1. Obtain all cookies by request:

cookie[] cookies = request.getcookies ();

2. Iterate through the cookie array and get the cookie we want by the name of the cookie

 for (Cookie cookie:cookies) {     if(Cookie.getname (). equal (CookieName)) {          =  Cookie.getvalue ();    }}

Complete Example:

//get data on cookies carried by the clientcookie[] Cookies =request.getcookies ();//Cookie cookie = new Cookie ("name", "Zhangsan");//get the cookie you want by using the cookie nameif(cookies!=NULL){     for(Cookie cookie:cookies) {//get the name of the cookieString CookieName =Cookie.getname (); if(Cookiename.equals ("name")){            //get the value of the cookieString Cookievalue =Cookie.getvalue ();        System.out.println (Cookievalue); }    }}

Exercise: Get the last time a user visited

//Get current TimeDate Date =NewDate (); SimpleDateFormat format=NewSimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"); String currenttime=Format.format (date);//1. Create a cookie to record the current time of the latest accessCookie cookie =NewCookie ("LastAccessTime"), currenttime); Cookie.setmaxage (60*10*500); Response.addcookie (cookie);//2. Get the client to carry a cookie----lastaccesstimeString LastAccessTime =NULL; Cookie[] Cookies=request.getcookies ();if(cookies!=NULL){     for(Cookie coo:cookies) {if("LastAccessTime". Equals (Coo.getname ())) {LastAccessTime=Coo.getvalue (); }}}response.setcontenttype ("Text/html;charset=utf-8");if(lastaccesstime==NULL) {response.getwriter (). Write ("You are the first to visit");}Else{response.getwriter (). Write ("The last time you visited was:" +lastaccesstime);}
View CodeSession Technology

Session technology is the technology that stores data on the server side, creating a memory space for each client to store the customer's data, but the client needs to carry an identity ID each time to go to the server to find its own memory space. So the implementation of the session is based on the cookie,session need to use cookies to store the unique identity of the customer Jsessionid.

Get Session Object
HttpSession session = Request.getsession ();

This method obtains a session object that is exclusively part of the current session, and if the session object that does not have the conversation on the server side creates a new session return, if there is already a session that belongs Session back (essentially, based on Jsessionid to determine if the client already exists on the server)

How to access data in session (session is also a domain object)

The session is also an area object that stores data, so the session object also has the following three methods:

Session.setattribute (String Name,object obj), Session.getattribute (string name), Session.removeattribute (string name );
some methods of Session object
    HttpSession session = request.getsession ();             // creation Time    System.out.println (Session.getlastaccessedtime ()); // Time of the last session visited    System.out.println (Session.getid ()  );   obtained SessionID    System.out.println (Session.getmaxinactiveinterval ());   Get maximum survival time

Setmaxinactiveinterval (int interval)
Invalidate immediately destroy session
System.out.println (Session.isnew ());//See if the currently acquired session is new. Only on the first access server, the session is new.
Session.invalidate ();

the life cycle of the session object

Created: The first time you execute Request.getsession () is created

Destroyed:

    1. When the server (abnormal) shuts down
    2. Session expiration/expiration (default 30 minutes)
when does the starting point of time begin to calculate 30 minutes?

start the timer by never manipulating the server-side resources, can be configured in the project's Web. XML

< Session-config > < Session-timeout ></session-timeout></session-config  >
Manually destroy session
Session.invalidate ();
function Range

The default is in a session, that is, any resource in a session is common to one of the sessions objects.

The browser closes and the session is destroyed?

No, the unique identifier Jsessionid (SessionID) that exists on the browser disappears, but the sessionid stored in the server is not destroyed immediately.

    • When multiple tabs are opened simultaneously in the same browser, sending the same request or a different request is still the same session;
    • When the same browser is not opened in the same window, sending the request is still the same session;
    • When using a different browser, send a request, even if sending the same request, is a different session;
    • When the window of the current browser is closed, then opened, and the same request is launched, it is a different session.

Verification Code Case:

 Packagesession;ImportCn.dsna.util.images.ValidateCode;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.io.IOException;/*** Created by Yang on 2017/7/24.*/ Public classSessiondemoextendsHttpServlet {@Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {doPost (req, resp); } @Overrideprotected voidDoPost (httpservletrequest request, HttpServletResponse resp)throwsservletexception, IOException {//1 Generate verification CodeValidatecode Code =NewValidatecode (200, 80, 4, 100);//2 Save the Verification code to the sessionSystem.out.println (Code.getcode ()); Request.getsession (). SetAttribute ("Code", Code.getcode ());//3 outputting The captcha picture to the browserResp.setcontenttype ("Image/jpeg");    Code.write (Resp.getoutputstream ()); }}
Sessiondemo
<%--Created by IntelliJ. User:yang Date:2017/7/23Time :11:34 to change ThisTemplate Use File | Settings |File Templates.--%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>Verification Code:<input type= "text" name= "code"/> <a href= "javascript:void (0)" onclick= "fun1 ();" > See a change </a><br> <input type= "Submit" value= "Login"/> <br></form><%= Request.getattribute ("error") = =NULL?"":( String) Request.getattribute ("error")%></body>function fun1 () {//1 Getting an IMG objectvar img = document.getElementById ("One"); //2 Changing the img object src attributeIMG.SRC = "/sessiondemo?abc=" +NewDate (); }</script>
index.jsp
 Packagesession;ImportCn.dsna.util.images.ValidateCode;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.io.IOException;/*** Created by Yang on 2017/7/24.*/ Public classDservletextendsHttpServlet {@Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {doPost (req, resp); } @Overrideprotected voidDoPost (httpservletrequest request, HttpServletResponse resp)throwsservletexception, IOException {//1 Get the verification code submitted by the formString Code1 = request.getparameter ("code"); //2 Get the correct verification code in sessionString code2 = (string) request.getsession (). getattribute ("code"); //3 The match is consistent        if(code1!=NULL&& code2!=NULL&&code1.equals (Code2)) {            //correct ==> Success pageResp.sendredirect ("/index.jsp"); }Else{            //Incorrect ==> back to form page with prompt errorRequest.setattribute ("Error", "CAPTCHA Error!)); Request.getrequestdispatcher ("/index.jsp"). Forward (request, RESP); }    }}
Dservlet

Javaweb study note Five-session technology Cookie&session

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.