Translated: Stackoverflow: Java Servlet working principle Q &,

Source: Internet
Author: User
Tags http cookie

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 numberServletWeb server. PassServletInformation transmittedServletContext, 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, ThenServletIs 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.ServletContextAnd save it in the memory of the server. Web Applicationweb.xmlResolved, find allservlet,filterAndListenerOr@WebServlet,@WebFilterAnd@WebListenerThe 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 reclaimServletContextAnd allServlet, Filter andListenerInstance.

When the problem occursServletConfiguredload-on-startupOr@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.xmlOr@WebServletClass 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 newHttpServletRequestAndHttpServletResponseObject, passed to the created and requested URL matchurl-patternOfFilterAndServletMethod 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 createHttpSessionTo generate a unique ID.session.getId()And stored in the server memory. Then, the Servlet containerSet-CookieSet a headerCookie,JSESSIONIDThe 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) mustCookieThe 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 determineCookieWhether the specified name exists in the headerJSESSIONIDAnd then use its value (session ID) to find the associatedHttpSession.

You canweb.xmlSet insession-timeoutThe default value is 30 minutes. Before timeout arrivesHttpSessionWill 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 newHttpSessionAnd set a newsessionID.

Overview
  • ServletContextSame 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.
  • HttpServletRequestAndHttpServletResponseThe 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,FilterAndListenerObjects are active during web application running. They are shared by requests in all sessions.
  • You setHttpServletRequest,HttpServletResponseAndHttpSessionAll 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.

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.