Javaweb Learning Summary (12)--session

Source: Internet
Author: User
Tags session id

First, the session simple introduction

In web development, the server can create a session object for each user browser (Session object), note that a browser exclusively has a Session object (by default). Therefore, when the user data needs to be saved, 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 can remove the user's data from the user's session, to serve the user.

Ii. key differences between session and Cookie
    • A cookie is a browser that writes the user's data to a user.
    • Session Technology writes the user's data to the user's 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 session implementation principle 3.1, the server is how to implement a session for a user browser service?

Server creation session, will be the session ID number, as a cookie back to the client, so as long as the client's browser is not closed, and then to access the server, will take the session ID number to go, the server found the client browser with session ID comes in, it will use the corresponding session in memory to serve. You can use the following code to prove that:

 1 package xdp.gacl.session; 2 3 Import java.io.IOException; 4 Import javax.servlet.ServletException; 5 Import Javax.servlet.http.HttpServlet; 6 Import Javax.servlet.http.HttpServletRequest; 7 Import Javax.servlet.http.HttpServletResponse; 8 Import javax.servlet.http.HttpSession; 9 public class SessionDemo1 extends HttpServlet {One to ten public void doget (HttpServletRequest request, Httpservletres Ponse response) throws Servletexception, IOException {response.setcharacterencoding ("utf=8"); 1 6 Response.setcontenttype ("Text/html;charset=utf-8"); 17//Use the Request object's getsession () to get the session, if the session does not exist Build a HttpSession session = Request.getsession (); 19//Store data in session session.setattribute ("data") , "aloof pale Wolf"); 21//Get session Id22 String sessionId = Session.getid (); 23//Determine if session is newly created     F (session.isnew ()) {Response.getwriter (). Print ("session is created successfully, the session ID is:" +sessionid); 26    }else {response.getwriter (). Print ("The server already exists, the session ID is:" +sessionid); 28}29}30 31 public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IO Exception {doget (request, response); 34}35}

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:

  

Click the Refresh button to request the server again, at this point you can see the browser to request the server, will be stored in the cookie in the session ID is passed to the server side, as shown in:

  

I guess the Request.getsession () method must have done the following after the new session was created inside

1//Get session Id2 String sessionId = Session.getid (); 3//Store the session ID in a cookie named Jsessionid 4 Cookie cookie = new Cookie ( "Jsessionid", sessionId); 5//Set the valid path of the cookie 6 Cookie.setpath (Request.getcontextpath ()); 7 Response.addcookie (cookie);
Iv. session processing After the browser disables Cookies 4.1, IE8 disable cookies
Tool->internet, privacy, settings, pull the slider to the top (Block all Cookies)

  

4.2. 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 the session after disabling the cookie

Indexservlet

 1 package xdp.gacl.session; 2 3 Import java.io.IOException; 4 Import Java.io.PrintWriter; 5 Import Java.util.LinkedHashMap; 6 Import Java.util.Map; 7 Import Java.util.Set; 8 Import javax.servlet.ServletException; 9 Import javax.servlet.http.httpservlet;10 Import javax.servlet.http.httpservletrequest;11 Import Javax.servlet.http.httpservletresponse;12 13//home: List all Books public class Indexservlet extends HttpServlet {All public void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {1         8 Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); 21 Create Session22 request.getsession (), Out.write ("This site has the following book:<br/>"); set<map.entry<s tring,book>> set = Db.getall (). EntrySet (); + for (map.entry<string,book> me:set) { Book = Me.getvalue (); String URL =request.getcontextpath () + "/sErvlet/buyservlet?id= "+ Book.getid ();//response. Encodeurl (Java.lang.string url) overrides the URL address of the form action and Hyperlink url = response.encodeurl (URL);//overrides the URL address of the hyperlink Out.println (Book.getname () + "<a href=" "+url+" > Purchase </a><br/> "); 31}32}33  public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doget (Request, response), PNS}38}39 all/**42 * @author gacl43 * Simulation Database */45 class Db{4 6 private static map<string,book> Map = new linkedhashmap<string,book> (); static{48 Map.put ( "1", New book ("1", "Javaweb development"), Map.put ("2", New book ("2", "Spring Development")), Map.put ("3", New book ("3", "Hi     Bernate development "); Map.put (" 4 ", New book (" 4 "," Struts Development ")), Map.put (" 5 ", New book (" 5 "," Ajax Development ")); 53}54 public static map<string,book> GetAll () {map;57 return     }58}59 class book{61 private string id;63 private string name;64 $ public book () {66 Super ();}68 public Book (string ID, string name) {this.id = id;71 This.nam         E = name;72}73 public String getId () {return id;75}76 public void setId (String id) {77 This.id = id;78}79 public String getName () {return name;81}82 public void SetName (String na Me) {this.name = name;84}85}

Buyservlet

 1 package xdp.gacl.session; 2 3 Import java.io.IOException; 4 Import java.util.ArrayList; 5 Import Java.util.List; 6 Import javax.servlet.ServletException; 7 Import Javax.servlet.http.HttpServlet; 8 Import Javax.servlet.http.HttpServletRequest; 9 Import javax.servlet.http.httpservletresponse;10 Import javax.servlet.http.httpsession;11 public class Buyservlet Extends HttpServlet {doget (httpservletrequest request, httpservletresponse response) Hrows servletexception, IOException {String id = request.getparameter ("id"), and page book = Db.getall ().  Get (ID); Get the book users want to buy HttpSession session = Request.getsession (); list<book> list = (list) Session.getattri  Bute ("list"); Get the container where the user holds all the books (list==null) {list = new arraylist<book> (); session.setattr Ibute ("list", list),}24 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/list Cartservlet "); System.out.println (URL); response.sendredirect (URL);}30 to public void Dopos         T (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {33 Doget (request, response); 34}35 36}

Listcartservlet

 1 package xdp.gacl.session; 2 3 Import java.io.IOException; 4 Import Java.io.PrintWriter; 5 Import Java.util.List; 6 Import javax.servlet.ServletException; 7 Import Javax.servlet.http.HttpServlet; 8 Import Javax.servlet.http.HttpServletRequest; 9 Import javax.servlet.http.httpservletresponse;10 Import javax.servlet.http.httpsession;11 public class Listcartservlet extends HttpServlet {$ public void doget (HttpServletRequest request, httpservletresponse response)         Throws Servletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8"); 17 PrintWriter out = Response.getwriter (); HttpSession session = Request.getsession (); LIST&LT;BOOK&G T List = (list) session.getattribute ("list"), if (List==null | | list.size () ==0) {Out.write ("Sorry, you have not purchased Buy any product! "); Return;23}24 25//Displays the product that the user has bought, Out.write ("You have bought the following goods:<br>"); or (book book:list) {28 Out.write (Book.getname () + "<br/>"),}30}31-public void DoPost (httpservletreques T request, httpservletresponse response) throws Servletexception, IOException {doget (Request, Res Ponse); 35}36}

The effect of IE8 with cookies disabled is as follows:

  

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

1 This website has the following book: <br/>javaweb development   <a href= '/javaweb_session_study_20140720/servlet/buyservlet;jsessionid= 96bdfb9d87a08d5ab1eaa2537cde2db2?id=1 ' > Purchase </a><br/>2 Spring development   <a href= '/javaweb_session_ study_20140720/servlet/buyservlet;jsessionid=96bdfb9d87a08d5ab1eaa2537cde2db2?id=2 ' > Purchase </a><br/> 3 Hibernate development   <a href= '/javaweb_session_study_20140720/servlet/buyservlet;jsessionid= 96bdfb9d87a08d5ab1eaa2537cde2db2?id=3 ' > Buy </a><br/>4 Struts development   <a href= '/javaweb_session_ Study_20140720/servlet/buyservlet;jsessionid=96bdfb9d87a08d5ab1eaa2537cde2db2?id=4 ' > Purchase </a><br/> 5 Ajax Development   <a href= '/javaweb_session_study_20140720/servlet/buyservlet;jsessionid= 96bdfb9d87a08d5ab1eaa2537cde2db2?id=5 ' > Purchase </a><br/>

Therefore, when the browser disables the cookie, you can rewrite the solution with the URL to solve the session data sharing problem. and response. Encoderedirecturl (java.lang.String URL) and response. Encodeurl (java.lang.String URL) is two very intelligent methods that do not make URL rewriting when the browser is detected without a cookie being disabled. We have access to Firefox with no cookies enabled, as follows:

As you can see from the demo animation, when the browser first accesses, the server creates a session, and then sends the session's ID back to the browser in the form of a cookie, response. The Encodeurl (java.lang.String URL) method also overrides the URL, and when the Refresh button is clicked, the second access, because Firefox does not disable cookies, so the second visit with 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 rewrite the URL.

V. Creation and destruction of Session objects time 5.1, Session object creation time

A new session is created when you first call the Request.getsession () method in your program, and you can use the IsNew () method to determine if the session is a newly created

Example: Creating a Session

1//Use the Request object's getsession () to get the session, or create a 2 HttpSession session = Request.getsession () If the session does not exist; 3//Get the session ID 4 String sessionId = Session.getid (); 5//Determine if the session is the newly created 6 if (Session.isnew ()) {7     response.getwriter (). Print ("session created successfully, session ID is:" +sessionid) ; 8}else {9     response.getwriter (). Print ("The ID of the server already exists Session,session is:" +sessionid); 10}
5.2. Time of destruction of Session object

Session object default 30 minutes is not used, the server will automatically destroy the session, in the Web. xml file can be manually configured session failure time, for example:

1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <web-app version= "2.5"  3     xmlns= "http://java.sun.com/xml/ Ns/javaee "  4     xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "  5     xsi:schemalocation=" http ://java.sun.com/xml/ns/javaee  6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> 7   < Display-name></display-name> 8    9   <welcome-file-list>10     <welcome-file> Index.jsp</welcome-file>11   </welcome-file-list>12   <!--set the session's effective time: in minutes and  -     <session-config>15         <session-timeout>15</session-timeout>16     </ Session-config></web-app>

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

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

Javaweb Learning Summary (12)--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.