Learning notes for session objects in Javaweb _java

Source: Internet
Author: User
Tags session id sessions

A brief introduction of the session

In web development, a server can create a session object for each user's browser, note: A browser is exclusive to a sessions object (by default). Therefore, when you need to save the user data, the server program can write the user data to the user's browser exclusive session, when users use the browser to access other programs, other programs from the user's session to take out the user's data, for the user Service.

Second, the main difference between session and Cookie

A Cookie is a browser that writes the user's data to the user.
The session technology writes the user's data to the user exclusive session.
The Session object is created by the server, and the developer can invoke the GetSession method of the request object to get the session object.

Third, the implementation of the principle of session

3.1, the server is how to implement a session for a user browser service?

Server created session, will be the ID number of sessions to the form of a cookie to the client, so that, as long as the client's browser does not close, then to access the server, will carry the session ID number, server Discovery client browser with session ID comes in, it will use the corresponding session in memory for the service. You can use the following code to prove:

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 Respo
    NSE) throws Servletexception, IOException {response.setcharacterencoding ("utf=8");
    Response.setcontenttype ("Text/html;charset=utf-8");
    Gets the session using the GetSession () of the Request object, and creates a HttpSession session = Request.getsession () If the session does not exist;
    Store data into session session.setattribute ("Data", "aloof Wolf");
    Gets the id String sessionId = session.getid () of the session;
    Determines whether the session is newly created if (Session.isnew ()) {Response.getwriter (). Print ("session was created successfully, session ID is:" +sessionid);
    }else {response.getwriter (). Print ("The server already exists, the session ID is:" +sessionid); }} public VOID DoPost (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {doGe
  T (request, response);

 }
}

On the first visit, the server creates a new sesion and sends the session ID as a cookie to the client browser, as shown in the following illustration:

Click the Refresh button, and then request the server again, you can see the browser to request the server, will be stored in the cookie session ID passed to the server side, as shown in the following figure:

I suspect that after the Request.getsession () method has created a session, it must have been handled as follows

Gets the id
String sessionId = Session.getid () of the session;
Store the session ID in a cookie named Jsessionid cookie
= new Cookie ("Jsessionid", sessionId);
Set a valid path for the cookie
Cookie.setpath (Request.getcontextpath ());
Response.addcookie (cookie);

Iv. session processing after browser disables cookies

4.1. IE8 Disable Cookies

Tools->internet options-> privacy-> settings-> pull the slider to the top (Block all Cookies)
4.2, the solution: URL rewrite

The Response.encoderedirecturl (java.lang.String URL) is used to override the URL address after the Sendredirect method.
Response.encodeurl (java.lang.String URL) is used to override the URL address of the form action and hyperlink

4.3. Example: The servlet shares the data in session 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, Httpservletres
    Ponse response) throws Servletexception, IOException {response.setcontenttype ("text/html;charset=utf-8");
    PrintWriter out = Response.getwriter ();
    Create session request.getsession ();
    Out.write ("This website has the following book:<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) for form action and hyperlinksURL to rewrite url = response.encodeurl (URL);//rewrite the URL address of the hyperlink out.println (Book.getname () + "<a href=" "+url+"
    ' > Buy </a><br/> '); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexc
  eption {doget (request, response); }/** * @author GACL * Analog 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 respons
    E) 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 if (list==null) {list = new arraylist<book> () for the user to save all books;
    Session.setattribute ("list", list);
    } list.add (book); Response. Encoderedirecturl (java.lang.String URL) is used to override 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, Ioexcepti
  On {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 re
    Sponse) 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 have not purchased any goods!!");
    Return
    Out.write ("You have bought the following goods:<br>")//show the goods purchased by the user;
    for (book book:list) {out.write (Book.getname () + "<br/>"); } public void DoPost (HttpServletRequest request, HttpSErvletresponse response) throws Servletexception, IOException {doget (request, response);

 }
}

The effect under IE8 with cookies disabled is as follows:

Demo effect

By looking at the HTML code generated by Indexservlet, you can see that each hyperlink is followed by a session ID, as shown below

 This site 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 ' > Buy </a><br/>//Hibernate development <a href= '/javaweb_session_study_20140720/servlet/buyservlet;jsessionid= 96bdfb9d87a08d5ab1eaa2537cde2db2?id=3 ' > Buy </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 ' > Buy </a><br/> 

So, when the browser disables cookies, you can rewrite this solution with a URL to resolve session data sharing problems. and response. Encoderedirecturl (java.lang.String URL) and response. Encodeurl (java.lang.String URL) is two very intelligent methods that do not overwrite URLs when they detect that the browser does not disable cookies. We have access to Firefox without disabling cookies, with the following effect:

As you can see from the demo animation, the first time the browser accesses, the server creates a session and then sends the session ID as a cookie back to the browser, response. The Encodeurl (java.lang.String URL) method also rewrites the URL, and when the second visit to the Refresh button is clicked, because the Firefox browser does not disable cookies, the second visit takes a cookie. At this point the server can know that the current client browser does not disable cookies, then notify response. The Encodeurl (java.lang.String URL) method does not have to override the URL.

The time of creation and destruction of the session object

5.1, the Session object creation time

A new session is created the first time the Request.getsession () method is called in the program, and the IsNew () method can be used to determine whether the session is newly created

Example: Creating a Session

Gets the session using the GetSession () of the Request object, and creates a
HttpSession session = Request.getsession () If the session does not exist;
Gets the id
String sessionId = Session.getid () of the session;
Determines whether the session is newly created
if (session.isnew ()) {
  response.getwriter (). Print ("session was created successfully, session ID is:" + sessionId);
} else {
  response.getwriter (). Print ("The server already exists session,session ID is:" +sessionid);
}

5.2, the time to destroy the session object

The session object is not used for 30 minutes by default, and the server automatically destroys sessions, and in the Web.xml file, you can manually configure the session expiration time, for example:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app version=
"2.5" xmlns= "http://java.sun.com/xml/ns/" 
  Java ee " 
  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 for the session: in minutes-->
  <session-config>
    < session-timeout>15</session-timeout>
  </session-config>

</web-app>

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

1 HttpSession session = Request.getsession ();
2//Manual call Session.invalidate method, destroy session
3 Session.invalidate ();

The above is the entire content of this article, I hope to learn a session to help you.

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.