Home>

A brief introduction to session

WebIn web development, the server can create a session object (session object) for each user's browser. Note:A browser has exclusive session object (by default). Therefore, when user data needs to be saved,The server program can write user data into a session exclusive to the user's browser. When the user uses the browser to access other programs,Other programs can fetch the user's data from the user's session,Serving users.

Second, the main difference between session and cookie

cookieWrites the user's data to the user's browser.

sessionThe technology writes the user's data into the user's exclusive session.

sessionObjects are created by the server,Developers can call the getsession method of the request object to get the session object.

Third, the principle of session implementation

3.1. How does the server implement a session to serve a user's browser?

After the server creates the session, it will write back the session id number to the client in the form of a cookie.This way, as long as the client ’s browser is not closed,When I visit the server again,Will go with the session id number, the server finds that the client browser came with the session id, it will use the corresponding session in memory to serve it.Can be proved with the following code:

package xdp.gacl.session;
import java.io.ioexception;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;
public class sessiondemo1 extends httpservlet {
  public void doget (httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    response.setcharacterencoding ("utf=8");
    response.setcontenttype ("text/html;charset=utf-8");
    //Use the request object's getsession () to obtain the session, if the session does not exist, create one
    httpsession session=request.getsession ();
    //Store data in the session
    session.setattribute ("data", "Lonely Wolf");
    //Get the session id
    string sessionid=session.getid ();
    //Determine if the session is newly created
    if (session.isnew ()) {
      response.getwriter (). print ("session created successfully,The session id is:"+ sessionid);
    } else {
      response.getwriter (). print ("The session already exists on the server, the session id is:" + sessionid);
    }
  }
  public void dopost (httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    doget (request, response);
  }
}

On your first visit,The server will create a new session and send the session id to the client browser as a cookie.As shown below:

Click the refresh button,Request the server again,At this point you can see that when the browser requests the server again,Will pass the session id stored in the cookie to the server,As shown below:

I guess the request.getsession () method must do the following processing after a new session is created

//Get the session id
string sessionid=session.getid ();
//Store the session id in a cookie named jsessionid
cookie cookie=new cookie ("jsessionid", sessionid);
//Set the effective path of the cookie
cookie.setpath (request.getcontextpath ());
response.addcookie (cookie);

Fourth, the session processing after the browser disables cookies

4.1, ie8 disable cookies

Tools->Internet Options->Privacy->Settings->Pull the slider to the top (block all cookies)

4.2 Solution:URL Rewriting

Response.encoderedirecturl (java.lang.string url) is used to rewrite the URL address after the sendredirect method.

Response.encodeurl (java.lang.string url) is used to rewrite the URL address of form action and hyperlink

4.3. Example:servlet sharing session data after disabling cookies

indexservlet

package xdp.gacl.session;
import java.io.ioexception;
import java.io.printwriter;
import java.util.linkedhashmap;
import java.util.map;
import java.util.set;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
//Home:List all books
public class indexservlet extends httpservlet {
  public void doget (httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    response.setcontenttype ("text/html;charset=utf-8");
    printwriter out=response.getwriter ();
    //Create session
    request.getsession ();
    out.write ("This site has the following books:<br />");
    set<map.entry<string, book>>set=db.getall (). entryset ();
    for (map.entry<string, book>me:set) {
      book book=me.getvalue ();
      string url=request.getcontextpath () + "/servlet/buyservlet?id =" + book.getid ();
      //response. encodeurl (java.lang.string url) is used to rewrite the URL address of form action and hyperlink
      url=response.encodeurl (url);//Rewrite the URL address of the hyperlink
      out.println (book.getname () + "<a href =" "+ url +" ">purchase</a><br />");
    }
  }
  public void dopost (httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    doget (request, response);
  }
}
/**
 * @author gacl
 * Simulation database
 * /
class db {
  private static map<string, book>map=new linkedhashmap<string, book>();
  static {
    map.put ("1", new book ("1", "javaweb development"));
    map.put ("2", new book ("2", "spring development"));
    map.put ("3", new book ("3", "hibernate development"));
    map.put ("4", new book ("4", "struts development"));
    map.put ("5", new book ("5", "ajax development"));
  }
  public static map<string, book>getall () {
    return map;
  }
}
class book {
  private string id;
  private string name;
  public book () {
    super ();
  }
  public book (string id, string name) {
    super ();
    this.id=id;
    this.name=name;
  }
  public string getid () {
    return id;
  }
  public void setid (string id) {
    this.id=id;
  }
  public string getname () {
    return name;
  }
  public void setname (string name) {
    this.name=name;
  }
}

buyservlet

package xdp.gacl.session;
import java.io.ioexception;
import java.util.arraylist;
import java.util.list;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;
public class buyservlet extends httpservlet {
  public void doget (httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    string id=request.getparameter ("id");
    book book=db.getall (). get (id);//Get the book the user wants to buy
    httpsession session=request.getsession ();
    list<book>list=(list) session.getattribute ("list");//Get the container the user uses to hold all books
    if (list == null) {
      list=new arraylist<book>();
      session.setattribute ("list", list);
    }
    list.add (book);
    //response. encoderedirecturl (java.lang.string url) is used to rewrite the URL address after the sendredirect method
    string url=response.encoderedirecturl (request.getcontextpath () + "/servlet/listcartservlet");
    system.out.println (url);
    response.sendredirect (url);
  }
  public void dopost (httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    doget (request, response);
  }
}

listcartservlet

package xdp.gacl.session;
import java.io.ioexception;
import java.io.printwriter;
import java.util.list;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;
public class listcartservlet extends httpservlet {
  public void doget (httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    response.setcontenttype ("text/html;charset=utf-8");
    printwriter out=response.getwriter ();
    httpsession session=request.getsession ();
    list<book>list=(list) session.getattribute ("list");
    if (list == null || list.size () == 0) {
      out.write ("Sorry, you haven't purchased any products !!");
      return;
    }
    //Show the products that users have bought
    out.write ("You have bought the following products:<br>");
    for (book book:list) {
      out.write (book.getname () + "<br />");
    }
  }
  public void dopost (httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    doget (request, response);
  }
}

The operation effect under ie8 with cookies disabled is as follows:

Presentation effect

You can see by viewing the html code generated by indexservlet,Each hyperlink is followed by the session id, as shown below

//This website has the following books:
<br />javaweb development
<a href="/javaweb_session_study_20140720/servlet/buyservlet;jsessionid=96bdfb9d87a08d5ab1eaa2537cde2db2?id=1">purchase</a><br />
//spring development
<a href="/javaweb_session_study_20140720/servlet/buyservlet;jsessionid=96bdfb9d87a08d5ab1eaa2537cde2db2?id=2">Purchase</a><br />
//hibernate development
<a href="/javaweb_session_study_20140720/servlet/buyservlet;jsessionid=96bdfb9d87a08d5ab1eaa2537cde2db2?id=3">Purchase</a><br />
//struts development
<a href="/javaweb_session_study_20140720/servlet/buyservlet;jsessionid=96bdfb9d87a08d5ab1eaa2537cde2db2?id=4">Purchase</a><br />
//ajax development
<a href="/javaweb_session_study_20140720/servlet/buyservlet;jsessionid=96bdfb9d87a08d5ab1eaa2537cde2db2?id=5">Purchase</a><br />

Therefore, when cookies are disabled by the browser, this solution can be rewritten with url to solve the session data sharing problem.And response. Encoderedirecturl (java.lang.string url) and response. Encodeurl (java.lang.string url) are two very smart methods,When it is detected that the browser has not disabled cookies, then url rewriting is not performed. We access it in Firefox without cookies disabled,The effect is as follows:

As you can see from the demo animation,When the browser first visits,The server creates a session, and then sends the session id back to the browser in the form of a cookie.response. encodeurl (java.lang.string url) method also rewrites the url,When the refresh button is clicked for the second visit,Because Firefox browser does not disable cookies, the cookie is brought on the second visit. At this time, the server can know that the current client browser has not disabled cookies, so it will notify response. Encodeurl (java.lang.string url) The method does not need to rewrite the url.

Five, the timing of the creation and destruction of the session object

5.1, the timing of the creation of the session object

A new session will be created when the request.getsession () method is called for the first time in the program. You can use the isnew () method to determine whether the session is newly created

Example:Create a session

//Use the request object's getsession () to obtain the session, if the session does not exist, create one
httpsession session=request.getsession ();
//Get the session id
string sessionid=session.getid ();
//Determine if the session is newly created
if (session.isnew ()) {
  response.getwriter (). print ("session created successfully,The session id is:"+ sessionid);
} else {
  response.getwriter (). print ("The session already exists on the server, and the session id is:" + sessionid);
}

5.2. Destroy timing of session object

Session object is not used by default for 30 minutes,The server will automatically destroy the session. You can manually configure the expiration time of the session in the web.xml file.E.g:

<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.5"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  xsi:schemalocation="http://java.sun.com/xml/ns/javaee
  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <display-name></display-name>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <!-Set the effective time of the session:in minutes->
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>
</web-app>

When you need to manually set the session invalidation in the program, you can manually call the session.invalidate method to destroy the session.

1 httpsession session=request.getsession ();

2 //Call the session.invalidate method manually to destroy the session

3 session.invalidate ();

  • Previous Chapter 47 of Manipulating Data in ASPNET 20: Inserting, Updating, and Deleting Data with the SqlDataSource Control
  • Next JS component Bootstrap achieves picture carousel effect