Java+servlet Working principle Quiz

Source: Internet
Author: User
Tags http cookie session id unique id server memory apache tomcat

This article comes from StackOverflow's question and answer, discusses the working mechanism of Java servlet, how to instantiate, share variables and multithreading.

Question: How does a servlet work? How does the Servlet instantiate, share variables, and multithreading?

Let's say I have a Web server that runs a large number of servlets. Transfer information between Servlets to get the servlet context and set session variables.

Now, if there are two or more users sending a request to the service, what happens to the session variable next? Are all users using common variables? Or are the variables used differently by different users? If this is the latter, how does the server differentiate between different users?

Another similar question, if a *n* user accesses a particular servlet, is the servlet instantiated only when the first user accesses it for the first time, or separately for each user?

Answer (BALUSC): ServletContext

When a Servlet container (such as Apache Tomcat) is started, all Web apps are deployed and loaded. When the web app is loaded, the Servlet container creates a servletcontext once and then saves it in the server's memory. Web application XML is parsed to find all of its servlet, filter, and Listener or @WebServlet, @WebFilter, and @WebListener annotations, created once and saved to the server's memory. Init () is called immediately for all filters. When the Servlet container is stopped, all Web apps are uninstalled, all initialized servlet and filter Destroy () methods are called, and finally the ServletContext and all servlet, filter, and Listener instances are reclaimed.

When the Load-on-startup or @WebServlet (loadonstartup) of the Servlet configuration in the problem is set to a value greater than 0, the init () method is also called immediately at startup. The values in "Load-on-startup" indicate that those servlets will be initialized in the same order. If the configured values are the same, they follow the order specified in Web. xml or the order in which the classes are loaded @WebServlet. Also, if you do not set the "Load-on-startup" value, the init () method is called only if the first HTTP request hits the Servlet in question.

HttpServletRequest and HttpServletResponse

The Servlet container is attached to a Web service that listens for HTTP requests on a port number, which is typically 8080 in the development environment and typically 80 in the production environment. When the client (Web browser) sends an HTTP request, the Servlet container creates a new HttpServletRequest and HttpServletResponse object that is passed to the created and requested URL that matches the Url-pattern F Ilter and the methods in the Servlet instance, all work is handled in the same thread.

The request object can access all the information in the HTTP request, such as the request header and request body. The response object provides you with the required control and sending HTTP response methods, such as setting the header and body (usually with HTML content in the JSP file). When the HTTP response is submitted and completed, the request and response objects are recycled.

HttpSession

The first time a user accesses the web app, it gets HttpSession through Request.getsession () for the first time. The Servlet container will then create HttpSession, generating a unique ID (which can be obtained through Session.getid ()) and stored in server memory. The Servlet container then sets a cookie on the Set-cookie header of the HTTP response to Jsessionid as the cookie name, and that unique session ID as the value of the cookie.

In accordance with the HTTP cookie rules (the standard that the normal Web browser and Web server must follow), when the cookie is valid, the client (browser) is required to return this cookie in the cookie header of the subsequent request. Using the browser's built-in HTTP traffic monitor, you can view them (press F12 in Chrome, firefox23+, ie9+, and see the Net/network tab). The Servlet container determines whether a cookie named Jsessionid exists in the cookie header of each incoming HTTP request, and then uses its value (session ID) to find the associated HttpSession from the server's memory.

You can set session-timeout in Web. XML with a default value of 30 minutes. HttpSession will remain alive until the time-out arrives. So the Servlet container reclaims the session when the client no longer accesses the Web app for more than 30 minutes. Each subsequent request, even if the specified cookie name is no longer accessible to the same session. The Servlet container creates a new Cookie.

On the other hand, the session cookie on the client has a default time-to-live, which is as long as the browser instance is running. Therefore, when the client closes the browser instance (all tags and Windows), the session is recycled by the client. The new browser instance no longer sends the cookie associated with the session. A new Request.getsession () will return a new HttpSession and set a cookie with the new session ID.

Overview
    • ServletContext is as long as the web app survives. It is shared by all requests in the session.
    • HttpSession exists as long as the client has been interacting with the web app of the same browser instance and has not timed out.
    • The lifetime of HttpServletRequest and HttpServletResponse is the time at which the client sends completion to the full Response (Web page). Will not be shared by other places.
    • All Servlet, Filter, and Listener objects are active while the Web app is running. They are shared by all requests in the session.
    • All of the properties you set in HttpServletRequest, HttpServletResponse, and HttpSession will remain alive when the object in question survives.
Thread Safety

Even so, you may be most concerned about thread safety. You should now learn that the Servlet and filter are shared by all requests. That is one of the advantages of Java, which allows multiple different threads (reading HTTP requests) to use the same instance. Otherwise, the overhead of re-creating threads for each request is too expensive.

But you should also be aware that you should never assign data from any request or session field to an instance variable of a servlet or filter. It will be shared by all requests in all other sessions. That's non-thread safe! The following example shows the situation:

 public  class  exampleservlet extends   HttpServlet { private  Span style= "color: #000000;"     > Object Thisisnotthreadsafe;  protected  void  doget ( HttpServletRequest request, HttpServletResponse response) throws   Servletexception, IOException {Object thisisthreadsafe; Thisisnotthreadsafe  = Request.getparameter ("foo"); //  bad!!        Shared among all requests!  Thisisthreadsafe = Request.getparameter ("foo"); //  OK, this is the thread safe.   
Please refer to:
    • What is the difference between JSF, Servlet, and JSP?
    • The best choice for managing a Session in Java
    • Doget and DoPost in the Servlet
    • Servlets appear to synchronize multiple concurrent requests

Java+servlet Working principle Quiz

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.