Java servlet Working principle Quiz

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

Guide

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?

Suppose I have a large number Servlet of Web servers running. Servletthe context is obtained by transferring information between Servlet , and the session variable is set.

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 specific Servlet , Servlet is it only instantiated when the first user accesses it first, or is it instantiated for each user individually?

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 , and then saves it in the server's memory. Web. XML   is parsed to find all of these   servlet , filter  , and   Listener   or   @WebServlet , @WebFilter and   @WebListener The contents of the   annotations are created once and saved to the memory of the server. init () is called immediately for all filters. When the Servlet container is stopped, all Web apps are uninstalled, the Destroy ()   method of all initialized Servlets and filters is called, and the   is finally recycled; ServletContext   and all   Servlet , Filter and   Listener   instance.

When the problem is Servlet configured load-on-startup or @WebServlet(loadOnStartup) a value greater than 0 is set, the method is also called immediately at startup init() . 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 web.xml order specified in or the order in which @WebServlet the classes are loaded. 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 new HttpServletRequest and HttpServletResponse objects, passes to the method that was created and the requested URL matches url-pattern and the Filter Servlet instance, all work on the same thread In the process.

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

When a user accesses the Web app for the first time, it request.getSession() gets HttpSession for the first time. The Servlet container will then be created HttpSession , generating a unique ID (which can be session.getId() obtained) and stored in server memory. The Servlet container then sets a value in the header of the HTTP response as Set-Cookie Cookie JSESSIONID the Cookie name, that unique session ID 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 header of the subsequent request Cookie . 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 will determine if there is a cookie named in the header of each incoming HTTP request Cookie JSESSIONID , and then use its value (session ID) to find the association from the server-side memory HttpSession .

You can web.xml set it in session-timeout , the default value is 30 minutes. Will survive until the time-out arrives HttpSession . 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 one 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 one request.getSession() will return the new HttpSession and set a session cookie with the new ID.

Overview
    • ServletContextAs 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.
    • HttpServletRequestAnd HttpServletResponse the time of survival for the client to send completion to the full Response (Web page) to arrive at this time. Will not be shared by other places.
    • 所有 Servlet, Filter and Listener objects are active when the Web app is running. They are shared by all requests in the session.
    • All of the attributes 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:

1234567891011 public class ExampleServlet extends HttpServlet {    private 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 thread safe.    } }

The first two days in a group saw someone recommend an app called Ask Ah, you can send a question to answer that kind of, feel like Uber drops a taxi like, generally this kind of software comes up to throw money to red envelopes what, elder brother before brushed Uber's single have experience! Test several times should be able to brush, the registration of red envelopes and before the red envelope money, now I mention more than 50, visual can also brush more. PS, but as far as possible to ask technical related issues, otherwise easy to be blocked.

Have the technology can try, will not be Q I: QQ group 290551701

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.