Translated: Stackoverflow: Java Servlet working principle Q &,
Guide
This article is from stackoverflow's Q & A and discusses the working mechanism of Java Servlet, how to instantiate, share variables, and multi-thread processing.
Q: How does Servlet work? How does a Servlet instantiate, share variables, and process multiple threads?
Suppose I have a large numberServlet
Web server. PassServlet
Information transmittedServlet
Context, and set the session variable.
Now, if two or more users send requests to this service, what will happen to the session variable next? Are all users using common variables? Or are the variables used by different users different? In the latter case, how does the server differentiate different users?
Another similar problem, if*n*
Name user to access a specificServlet
, ThenServlet
Is it instantiated only when the first user accesses the object for the first time, or is it instantiated for each user separately?
Answer (BalusC): ServletContext
When the Servlet container (such as Apache Tomcat) is started, all web applications are deployed and loaded. When a web application is loaded, the Servlet container is created once.ServletContext
And save it in the memory of the server. Web Applicationweb.xml
Resolved, find allservlet
,filter
AndListener
Or@WebServlet
,@WebFilter
And@WebListener
The content of the annotation, which is created once and saved to the memory of the server. All filters are called immediately.init()
. When the Servlet container stops, all web applications will be uninstalled and all initialized servlets and filters will be called.destroy()
Method, and finally reclaimServletContext
And allServlet
, Filter andListener
Instance.
When the problem occursServlet
Configuredload-on-startup
Or@WebServlet(loadOnStartup)
If a value greater than 0 is set, it is also called at startup.init()
Method. The value in "load-on-startup" indicates that the servlets will be initialized in the same order. If the configuration values are the sameweb.xml
Or@WebServlet
Class Loading Order. In addition, if the "load-on-startup" value is not set,init()
The method is called only when the Servlet in the first HTTP request hits the problem.
HttpServletRequest and HttpServletResponse
The Servlet container is appended to a web service. This web service listens to HTTP requests on a port number. In the development environment, this port is usually 8080, and usually 80 in the production environment. When the client (web browser) sends an HTTP request, the Servlet container creates a newHttpServletRequest
AndHttpServletResponse
Object, passed to the created and requested URL matchurl-pattern
OfFilter
AndServlet
Method in the instance, all work is processed in the same thread.
The request object can access all information in the HTTP request, such as request header and request body. The response object provides you with the required control and HTTP response methods, such as setting the header and body (usually containing the HTML content in the JSP file ). After the HTTP response is submitted and completed, the request and response objects will be recycled.
HttpSession
When you access the web application for the first timerequest.getSession()
Obtain HttpSession for the first time. Then the Servlet container will createHttpSession
To generate a unique ID.session.getId()
And stored in the server memory. Then, the Servlet containerSet-Cookie
Set a headerCookie
,JSESSIONID
The Cookie name and the unique session IDCookie
.
According to the HTTP cookie rules (standard that must be followed by normal web browsers and web servers), when the cookie is valid, the client (browser) mustCookie
The cookie is returned in the header. You can view the HTTP traffic monitor built in the browser (Press F12 in Chrome, Firefox23 +, IE9 +, and then view the Net/Network label ). The Servlet container will determineCookie
Whether the specified name exists in the headerJSESSIONID
And then use its value (session ID) to find the associatedHttpSession
.
You canweb.xml
Set insession-timeout
The default value is 30 minutes. Before timeout arrivesHttpSession
Will survive. So when the client no longer accesses the web application for more than 30 minutes, the Servlet container will recycle the session. For each subsequent request, the same session cannot be accessed even if the cookie name is specified. The Servlet container creates a newCookie
.
On the other hand, the session cookie on the client has a default survival time, which is the same as the running time of the browser instance. Therefore, when the client closes the browser instance (all labels and Windows), the session will be recycled by the client. The new browser instance no longer sends the cookie associated with the session. A newrequest.getSession()
A newHttpSession
And set a newsession
ID.
Overview
ServletContext
Same as the survival time of web applications. It is shared by all requests in all sessions.
- HttpSession will exist as long as the client has been interacting with the web application of the same browser instance and does not time out.
HttpServletRequest
AndHttpServletResponse
The survival time of is the time when the client sends a complete response (web page. It will not be shared by other places.
All servlets
,Filter
AndListener
Objects are active during web application running. They are shared by requests in all sessions.
- You set
HttpServletRequest
,HttpServletResponse
AndHttpSession
All attributes in will remain alive when the objects in question survive.
Thread Security
Even so, you are most concerned about thread security. Now you should learn that Servlet and filter are shared by all requests. That is an advantage of Java, so that multiple different threads (read HTTP requests) can use the same instance. Otherwise, it is too expensive to re-create a thread for each request.
But you should also realize that you should never assign any data in the request or session field to the instance variables of servlet or filter. It will be shared by all requests in other sessions. That Is Not thread-Safe! The following example shows the situation:
public class ExampleServlet extends HttpServlet { private Object thisIsNOTThreadSafe; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object thisIsThreadSafe; thisIsNOTThreadSafe = request.setParameter("foo"); // BAD!! Shared among all requests! thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe. }}
See:
- What is the difference between JSF, Servlet, and JSP?
- Best Choice for managing sessions in Java
- DoGet and doPost in Servlet
- Servlet seems to process multiple concurrent requests synchronously
Original article: stackoverflow
Starting from: http://www.importnew.com/17025.html, and synchronized to Github. Welcome to Star.