1. A brief introduction to Session
In WEB development, the server can create a session object (session object) for each user's browser. Note: a browser exclusively owns a session object (by default). Therefore, when it is necessary to save user data, 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 retrieve the user's data from the user's session to serve the user.
2. The main differences between session and cookies
Cookies are the browser that writes user's data to users.
Session technology writes user data into user-owned sessions.
The Session object is created by the server, and developers can call the getSession method of the request object to get the session object.
3. Session implementation principle
3.1. How does a server implement a session to serve a user's browser?
After the server creates the session, it will write the session id number back to the client in the form of a cookie. In this way, as long as the client's browser is not closed, when accessing the server, it will bring the session id number. When the server finds that the client browser has the session id, it will use the corresponding session in memory to serve it. 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;import javax.servlet.http.HttpSession;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 getSession() of the request object to get the session. If the session does not exist, create an HttpSession session = request.getSession(); //Storage the data in the session session.setAttribute("data", "Lonely Canglang"); //Get the Id of the session String sessionId = session.getId(); //Judge whether the session is newly created if (session.isNew()) { response.getWriter().print("session was created successfully, the session's id is: "+sessionId); }else { response.getWriter().print("The session already exists in the server, the session's id is: "+sessionId); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}When accessing for the first time, the server will create a new session and send the session ID to the client browser in the form of a cookie, as shown in the figure below:
Click the refresh button and request the server again. At this time, you can see that when the browser requests the server again, the session ID stored in the cookie will be passed to the server side together, as shown in the figure below:
I guess the request.getSession() method must have done the following processing after the newly created Session inside
//Get the session IdString sessionId = session.getId();//Storage the session Id in the cookie with the name JSESSIONID Cookie cookie = new Cookie("JSESSIONID", sessionId);//Set the valid path of the cookie cookie.setPath(request.getContextPath()); response.addCookie(cookie);4. The session processing after the browser disables the cookies
4.1. IE8 disable cookies
Tools -> Internet Options -> Privacy -> Settings -> Pull the slider to the top (block all cookies)
4.2. Solution: URL rewrite
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 the form action and hyperlink
4.3. Example: After disabling cookies, servlets share data in the Session
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.HttpServletRequest;import javax.servlet.http.HttpServletResponse;//Homepage: 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 website 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 form action and the url address of the 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 * Simulate 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 that the user wants to buy HttpSession session = request.getSession(); List<Book> list = (List) session.getAttribute("list"); //Get the container used by the user to save 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 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 yet!!"); return; } //Show the products purchased by the user 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:
Demo effect
By looking at the html code generated by IndexServlet, you can see that each hyperlink has the session ID followed by, 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 the browser disables cookies, it can rewrite this solution with URLs to solve the Session data sharing problem. Moreover, 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 does not disable cookies, the URL rewrite will not be performed. We access it under Firefox browser without disabling cookies, the effect is as follows:
As can be seen from the demonstration 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. The response. encodeURL (java.lang.String url) method also rewritten the URL. When the refresh button is clicked for the second visit, the Firefox browser does not disable cookies, so it brings the cookie on the second visit. At this time, the server can know that the current client browser does not disable cookies, so it notifies the response. encodeURL (java.lang.String url) method that does not need to rewrite the URL.
5. The timing of creating and destroying session objects
5.1. The creation time of 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 getSession() of the request object to get the session. If the session does not exist, create an HttpSession session = request.getSession();//Get the IdString sessionId = session.getId();//Judge whether the session is newly created if (session.isNew()) { response.getWriter().print("session was created successfully, the session's id is: "+sessionId);}else { response.getWriter().print("The server already has session, the session's id is: "+sessionId);}5.2. Destruction timing of session object
The session object is not used for 30 minutes by default, and the server will automatically destroy the session. The failure time of the session can be manually configured in the web.xml file, for example:
<?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 valid 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 to fail in the program, you can manually call the session.invalidate method to destroy the session.
1 HttpSession session = request.getSession();
2 //Manually call the session.invalidate method to destroy the session
3 session.invalidate();
The above is all about this article, I hope it will be helpful for everyone to learn session.