In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
How to go deep into the Tomcat source code analysis of Session, in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
What on earth is Session?
As we all know, the HTTP protocol itself is Stateless, which is functional enough for some simple page presentation. For the increasingly complex dynamic pages, applications, a variety of login authentication and other scenarios, it is inadequate. Imagine what it would be like for a logged-in user to be prompted to log in again and again.
Therefore, for most applications that need to maintain state, it is necessary to ensure the consistency of the interaction state between the client and the server. For multiple requests initiated by the browser, only based on the HTTP protocol, it is impossible to identify whether the request is made by the same user. In order to maintain the interaction between the client and the server, a series of strategies can be adopted, such as:
Cookie
Hide form form fields
Session
URL
SSL
The following will examine how Session is used inside the most commonly used Servlet container to keep the client and server state consistent by delving into the Tomcat source code.
As Web application developers, we must have heard and even understood the word Session and some of the concepts behind it.
Session, called session in Chinese, is used to maintain the state when two devices interact with each other. Therefore, at least one party in the conversation needs to save the state of the conversation.
In the Servlet specification, the session object is represented by the interface HttpSession, and the interface description concisely summarizes its main role.
Provides a way to identify a user across more than one page request or
Visit to a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP
Client and an HTTP server. The session persists for a specified time period
Across more than one connection or page request from the user. A session
Usually corresponds to one user.
Inside Tomcat, HttpSession is implemented through StandardSession, and StandardSession is used to deal with it.
When you first request an application, if you need to use Session, it will be created. It is not directly used in general Servlet. If you are requesting a JSP file, because the default implicit object of JSP contains
Session, which, when generating the Servlet file, internally contains the
HttpServletRequest.getSession (true)
Therefore, the session object is created directly upon request.
The process of creating a session looks roughly like the following:
Protected Session doGetSession (boolean create) {
/ / There cannot be a session if no context has been assigned yet
Context context = getContext ()
If (context = = null) {
Return (null)
}
/ / Return the current session if it exists and is valid
If ((session! = null) & &! session.isValid ()) {
Session = null
}
If (session! = null) {
Return (session)
}
/ / Return the requested session if it exists and is valid
Manager manager = context.getManager ()
If (manager = = null) {
Return (null); / / Sessions are not supported
}
If (requestedSessionId! = null) {
Try {
Session = manager.findSession (requestedSessionId)
} catch (IOException e) {
Session = null
}
If ((session! = null) & &! session.isValid ()) {
Session = null
}
If (session! = null) {
Session.access ()
Return (session)
}
}
/ / Create a new session if requested and the response is not committed
If (! create) {
Return (null)
}
If (response! = null
& & context.getServletContext ()
.getEffectiveSessionTrackingModes ()
.clients (SessionTrackingMode.COOKIE)
& & response.getResponse () .isCommitted () {
Throw new IllegalStateException (
Sm.getString ("coyoteRequest.sessionCreateCommitted"))
}
/ / Attempt to reuse session id if one was submitted in a cookie
/ / Do not reuse the session id if it is from a URL, to prevent possible
/ / phishing attacks
/ / Use the SSL session ID if one is present.
If (("/" .equals (context.getSessionCookiePath ()
& & isRequestedSessionIdFromCookie () | | requestedSessionSSL) {
Session = manager.createSession (getRequestedSessionId ())
} else {
Session = manager.createSession (null)
}
/ / Creating a new session cookie based on that session
If (session! = null
& & context.getServletContext ()
.getEffectiveSessionTrackingModes ()
.clients (SessionTrackingMode.COOKIE)) {
Cookie cookie =
ApplicationSessionCookieConfig.createSessionCookie (
Context, session.getIdInternal (), isSecure ()
Response.addSessionCookieInternal (cookie)
}
If (session = = null) {
Return null
}
Session.access ()
Return session
}
The whole process is basically to determine whether a session already exists, and if not, create it. If so, use it directly.
At this point, there are two issues to pay attention to:
On the first request, how does session generate and pass to the client
In other subsequent requests, if the client's request is associated with the server's existing session
In the above code, the process of determining that the session does not exist and creating it is to call the createSession method directly and determine whether the session is completely newly created or the existing session is restored based on whether the sessionId is empty.
Public Session createSession (String sessionId) {
If ((maxActiveSessions > = 0) &
(getActiveSessions () > = maxActiveSessions)) {
RejectedSessions++
Throw new TooManyActiveSessionsException (
Sm.getString ("managerBase.createSession.ise")
MaxActiveSessions) / / notice that there is a strategy here.
}
/ / Recycle or create a Session instance
Session session = createEmptySession ()
/ / Initialize the properties of the new session and return it
Session.setNew (true)
Session.setValid (true)
Session.setCreationTime (System.currentTimeMillis ())
Session.setMaxInactiveInterval (this.maxInactiveInterval)
String id = sessionId
If (id = = null) {
Id = generateSessionId ()
}
Session.setId (id)
SessionCounter++
SessionTiming timing = new SessionTiming (session.getCreationTime (), 0)
Synchronized (sessionCreationTiming) {
SessionCreationTiming.add (timing)
SessionCreationTiming.poll ()
}
Return (session)
}
There is a Session timeout, the maximum idle time.
Note that the value of maxInactiveInterval, which is the session timeout provided in our default web.xml (background reply keyword 004, learn more), is 30 minutes.
After creating the Session, Tomcat returns the session data to the client by setting the MimeHeader of Set-Cookie in the response header. The data returned is as follows:
JSESSIONID=CC4D83F3A61823AA8F980C89890A19D7; Path=/manager/; HttpOnly
The procedure for setting up Header is as follows:
Public void addSessionCookieInternal (final Cookie cookie) {
If (isCommitted ()) {/ / it is judged here that if response has been submitted, it can no longer be set.
Return
}
String name = cookie.getName ()
Final String headername = "Set-Cookie"
Final String startsWith = name + "="
String header = generateCookieString (cookie); / / here, the corresponding string is generated according to the content of the specific cookie, and the version and expiration time of the cookie will be judged internally.
If (! set) {
AddHeader (headername, header)
}}
We see that the first request contains highlighted data in the response header.
As for the request again, we see that there is no sessionId data in the response header this time. Instead, it is transferred to the request header and provided in the form of Cookie:
At this point, it is passed to the server, and the server parses the JSESSIOONID corresponding to Cookie, and extracts the corresponding sessionID value, which is associated with the corresponding session data of the server.
Let's look at the implementation in the code
When you request again, the place to get the SessionCookie from Request is here:
CoyoteAdapter.postParseRequset ()
It internally calls parseSessionCookiesId (request) to parse the cookie data in the request header.
Public void parseCookieHeader (MimeHeaders headers, ServerCookies serverCookies) {
/ / process each "cookie" header
Int pos = headers.findHeader ("Cookie", 0)
}
}
It is important to note here that the name of SessionCookie is allowed to be configured, so this name may not always be JSESSIONID.
After parsing Cookie to get SessionId, all we get is a string that cannot be immediately associated with Session, so request assigns this value to its internal name
Properties of the requestSessionId.
When session is requested again later, as we see in the top code, there will be a process of findSession
At this point, we have a basic understanding of one of the implementation ways to maintain the consistency of the interaction state between the client browser and the server Tomcat, namely SessionCookie.
In essence, this process is a traditional Socket interaction process, we can write a piece of code to simulate the response data, but we need to note that the response header data has specific format requirements in the HTTP specification, that is, the data should be separated by CRLF.
To sum up, the client first requests the server to create a Session, which passes the sessionId to the client by setting the Set-Cookie in the response header. Subsequent client requests will set the Cookie entry with sessionId in the request header to ensure the consistency of the interaction state between the client and the server.
On how to in-depth Tomcat source code analysis of Session questions to share here, I hope the above content can be of some help to you, if you still have a lot of doubts have not been solved, you can follow the industry information channel to learn more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.