English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of JavaWeb Session Session Management

Session Introduction

Session refers to the interaction process between the user and the Web application within a certain period of time, using the same browser process.

Session (Session) is usually used to track user status and cache user information in the browser process.

When the user closes the browser, the previous session cannot be obtained again (the maxAge of the Cookie is-1In the case). When a new browser is opened, a new session will begin.

The class javax.servlet.http.HttpSession. Each HttpSession represents a session for a user.
The default expiration time of each session is30 minutes.

When the browser accesses the server for the first time, regardless of which page is accessed first, the server will assign a unique session identifier to the user, that is, jsessionid, and return it to the user in the form of a cookie.
The following is a response header (the following is based on Servlet3.0 in Servlet2.5There is no HttpOnly attribute)

The server creates a session for each user, that is, an HttpSession object, and stores it on the server side.

Then, how does the server know it is the same user when the user accesses the server again?

When the browser accesses the server again, it will carry a cookie containing jsessionid to access the server. The server returns the HttpSession object for this user based on this id, thus maintaining the session.
(So, can the same session be implemented on different browsers?)

Below is a typical URL with some deceptive effects, which can implement the same session on different browsers:

http://localhost:8080/day07_2/CNCookieServlet;jsessionid=F8692D61CD46D094DBB7A8FC7387649C )

The relationship between the browser and the server is shown in the following two diagrams:


HttpSession:

In Servlets, the session object is obtained through the HttpServletRequest.getSession method.

The following methods of the HttpSession interface are used to share data within the session scope:

getAttribute(“name”)
setAttribute(“name”,object);
getAttributeNames()
removeAttrubute(“name”)

Invalidate(); - This method forcibly deletes the server-cached session.

Example:

Set certain values in the httpSession of a Servlet by calling setAttribute.

Jump to other servlets through hyperlinks or other methods and display information by calling getAttribute.

Display information by calling getAttribute in any Servlet.

Close this browser and re-access the servlet that obtained the information, and you will find that there is no information.

As follows:

String name=request.getParameter("name"); 
request.setAttribute("name", "request---"+name); 
request.getSession().setAttribute("name", "session---"+name); 
getServletContext().setAttribute("name", "application---"+name); 

The unique identifier Id of Session:

Each Session has a unique identifier, that is, the ID.

When the browser gets a new Session, the user can print out the value of the ID through session.geId().

Without closing the browser, jumping between multiple pages uses the same Session.

For example:

request.getSession().getId() 

What is safe logout:

When a user logs out, they should clear their information from the Session - that is, perform a safe logout.

The purpose of safe logout is to clean up the information left on the server to prevent hacking.

Session.invalidate();

1request.getSession().invalidate();

This can delete the corresponding object in the session pool.

2Session.removeAttribute(…)

For example:

request.getSession().removeAttribute("realCode");

Used to delete properties from the session object

Session tracking through rewriting URLs:

As has been mentioned before, the Servlet container first saves a SessionID on the client side, and then, when the browser sends an HTTP request, it always includes this SessionID. The Servlet container reads this SessionID from the HTTP request, retrieves the HttpSession object from the container based on this SessionID, and uses it to track which session the HTTP request belongs to. This process is called session tracking.

If the browser supports cookies, the Servlet container will save the SessionID as a cookie on the browser's client side. But if the user disables cookies for security reasons, how does the Servlet container track the session?

First, let's disable cookies in IE (note: it does not work for some GHOST systems).

IE>Tools>Internet Options>Privacy>Advanced, then disable Cookie:

We can add such hyperlinks on the homepage: (The code related to SaveServlet.java, GetServlet.java, LogoutServlet.java is attached at the end)

<h2>Demonstration of URL rewriting technology---Resolving the issue of an invalid session after the user disables cookies</h2> 
<form action="<%=response.encodeURL("saveServlet") %>" method="post"> 
name:<input type="text" name="name"/><br/> 
<input type="submit"/> 
</form> 
<a href="<%=response.encodeURL("getServlet") %>">Rewrite url-Read data from several containers</a><br/> 
<a href="<%=response.encodeURL("logoutServlet") %>">Rewrite url-Secure logout</a> 

This sentence<form action=“<%=response.encodeURL(“/aa”)%>”>to achieve this function

After disabling cookies here, the browser can still receive cookies sent by the server, but it can only accept and not send them back to the server. If cookies cannot be sent, it is also not possible to retrieve the corresponding object from the session pool.

After entering the desired value in the form, access the hyperlink at the following getServlet to see if the entered value is still displayed. The answer is affirmative. The access path is similar to

http://localhost:8080/day07_2/CNCookieServlet;jsessionid=F8692D61CD46D094DBB7A8FC7387649C The, followed by the jsessionid=F8692D61CD46D094DBB7A8FC7387649C is its id. Thus, you can access it by entering this URL in another browser.
Here, I would like to add: (The following situation is when I write the JSESSIONID value and value of the HttpSession object in the session pool to the cookie, which will overwrite the system-generated cookie, so it is equivalent to me creating it myself. I set the existence time to ten minutes. If it is not overwritten, the cookie will be deleted when the browser is closed, and the following phenomenon will not occur)

In both cases of disabling and not disabling cookies, the id of the newly created object in the session pool is different, that is, if you enter a name value in the form when cookies are disabled, the query results will be as follows:

and the jsessionid is2BB51EBDEAAF14D19656C71E1B6F9FF6

Then, immediately switch to the non-disabling cookie mode, enter another name such as Tom, and the query results will naturally be two Toms, with the jsessionid as

203F9E4DB5D874476B81DAF350661B6A, this is different from disabling, which results in the following

Then, we close the browser, open it again, and view the access results without disabling cookie mode, as follows:

Below, I will paste the main code:

SaveServlet.java

package cn.hncu.servlets.session; 
import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.http.Cookie; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
public class SaveServlet extends HttpServlet { 
public void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
doPost(request, response); 
} 
public void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
response.setContentType("text/html;charset=utf-8"); 
PrintWriter out = response.getWriter(); 
request.setCharacterEncoding("utf-8"); 
String name=request.getParameter("name"); 
request.setAttribute("name", "request---"+name); 
request.getSession().setAttribute("name", "session---"+name); 
getServletContext().setAttribute("name", "application---"+name); 
//This is an example of combining cookie technology and session technology for application development---※Function: To allow users to retain data after closing the browser, if10you can log in to this site within minutes and access the information in the session. 
//Write a cookie to the client with the key "JSESSIONID" and the value "sessionid", 
Cookie c=new Cookie("JSESSIONID", request.getSession().getId()); 
c.setMaxAge(60*10;//The phenomenon above is caused by this sentence, without this sentence, there would not be the phenomenon mentioned above. 
c.setPath(request.getContextPath()); 
response.addCookie(c); 
out.println("Saved successfully..."); 
out.flush(); 
out.close(); 
} 
}

GetServlet.java

package cn.hncu.servlets.session; 
import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
public class GetServlet extends HttpServlet { 
public void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
response.setContentType("text/html;charset=utf-8"); 
PrintWriter out = response.getWriter(); 
out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN>"; 
out.println("<HTML>"; 
out.println("<HEAD><TITLE>A Servlet</TITLE></HEAD>"; 
out.println("<BODY>"; 
String reqName=(String) request.getAttribute("name"); 
String seName=(String) request.getSession().getAttribute("name"); 
String appName=(String) getServletContext().getAttribute("name"); 
out.println(reqName+"<br/>"; 
out.println(seName+"<br/>"; 
out.println(appName+"<br/>"; 
out.println("</BODY>"; 
out.println("</HTML>"; 
out.flush(); 
out.close(); 
} 
}

LogoutServlet.java

package cn.hncu.servlets.session; 
import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
public class LogoutServlet extends HttpServlet { 
public void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
response.setContentType("text/html;charset=utf-8"); 
PrintWriter out = response.getWriter(); 
//Safe Logout---Just make the session object invalid 
request.getSession().invalidate(); 
out.println("Already safely logged out..."); 
} 
} 

The above is the JavaWeb Session session management introduced by the editor for everyone. I hope it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time!

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright. It has not been manually edited and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like