"Servlet" Working principle analysis 2

Source: Internet
Author: User

Create a Servlet instance

The Servlet's parsing work has been completed and is packaged as Standardwrapper added to the Context container, but it still does not work for us, it has not yet been instantiated. Here we describe how the Servlet object was created and how it was initialized.

Create a Servlet object

If the Servlet's Load-on-startup configuration entry is greater than 0, it will be instantiated when the Context container is started, and the default globalwebxml is read when parsing the configuration file, and some are defined in the Web. xml file under CONF. The default configuration item, which defines two servlets, are: Org.apache.catalina.servlets.DefaultServlet and org.apache.jasper.servlet.JspServlet their Load-on-startup are 1 and 3, which means that two servlets will be started when Tomcat is started.

The way to create a Servlet instance is from Wrapper. The Loadservlet began. The Loadservlet method is to get servletclass and give it to Instancemanager to create a Servletclass.class-based object. If this Servlet is configured with Jsp-file, then this servletclass is the Org.apache.jasper.servlet.JspServlet defined in Conf/web.xml.

The related class structure diagram for creating a Servlet object is as follows:

Figure 3. Create a related class structure for a Servlet object

Initialize Servlet

Initializing the servlet in Standardwrapper's Initservlet method, this method is simple to invoke the Servlet's Init method, while wrapping the Standardwrapper object's Standardwrapper Facade passed as ServletConfig to the Servlet. Why the Tomcat container is passed Standardwrapperfacade to the Servlet object will be parsed in detail later.

If the Servlet is associated with a JSP file, then the Jspservlet is initialized, and then a simple request is emulated, and the JSP file is called to compile the JSP file as class and initialize the class.

The Servlet object is initialized so that the servlet is actually parsed from Web. XML to complete initialization, a process that is very complex, with many processes in between, including the triggering of monitoring events caused by conversions of various container states, control of various access rights, and the award of unforeseen errors. Behavior and so on. We have only scratched some key links here to illustrate, trying to get everyone to have a general context.

The following is a complete sequence diagram of the process, which also omits some of the details.

Figure 4. Initialize the Servlet's timing diagram

Servlet Architecture

We know that Java WEB applications operate on the basis of servlet specifications, so how does the servlet itself work? Why design such an architecture.

Figure 5.Servlet Top level class correlation diagram

It can be seen that the servlet specification is based on these classes, with the servlet actively associated with three classes, namely ServletConfig, ServletRequest, and Servletresponse. These three classes are passed through the container to the servlet, where ServletConfig is passed to the servlet when the servlet is initialized, and then two is called by the servlet simultaneous when the request is reached. We know the meaning of ServletRequest and servletresponse in the servlet, but what is the value of ServletConfig and ServletContext for Servlets? Looking closely at the methods declared in the ServletConfig interface, these methods are intended to obtain some of the configuration properties of this servlet, which may be used when the servlet is running. And what does ServletContext do? The Servlet's operating mode is a typical "handshake-type interactive" run mode. The so-called "handshake Interactive" is two modules in order to exchange data will usually prepare a trading scene, this scene has been following a trading process until the transaction is complete. The initialization of this trading scenario is customized based on the parameters specified by the transaction object, which is usually a configuration class. Therefore, the trading scene is described by ServletContext, and the custom parameter set is described by ServletConfig. ServletRequest and Servletresponse are specific objects to interact with, and they are often used as transport tools to communicate the results of interactions.

ServletConfig was passed from the container at the time of the Servlet init, so what is ServletConfig?

is the class diagram of ServletConfig and ServletContext in the Tomcat container.

Figure 6. ServletConfig class correlation diagram in a container

The figure above shows that both Standardwrapper and Standardwrapperfacade implement the ServletConfig interface, and Standardwrapperfacade is the Standardwrapper façade class. So the Standardwrapperfacade object is passed to the Servlet, which guarantees that the data provided by the ServletConfig is taken from the standardwrapper without exposing the data that ServletConfig does not care about to S Ervlet.

Similarly ServletContext also has a similar structure to servletconfig, and the actual object of the ServletContext that can be obtained in the Servlet is also the Applicationcontextfacade object. Applicationcontextfacade also guarantees that Servletcontex can only get the data it takes from the container, and they all play a role in encapsulating the data, and they use the façade design pattern.

Through ServletContext you can get some necessary information in the Context container, such as the working path of the application, the minimum version of Servlet supported by the container, etc.

What are the actual objects of the two servletrequest and Servletresponse defined in the Servlet? , we typically use httpservletrequest and httpservletresponse when creating our own Servlet classes, which inherit ServletRequest and Servletresponse. Why do the ServletRequest and servletresponse that the Context container passes over can be converted to HttpServletRequest and httpservletresponse?

Figure 7.Request Related class structure diagram

The diagram above is a class diagram of Request and Response created by Tomcat. Tomcat one acceptance to the request will first create org.apache.coyote.Request and Org.apache.coyote.Response, which are two classes that are used internally by Tomcat to describe a request and the corresponding information classes they are a lightweight class , their role is that after the server receives the request, after the simple resolution will quickly allocate this request to the subsequent thread to deal with, so their object is very small, it is easy to be recycled by the JVM. Then the org.apache.catalina.connector is created when a user thread is handed over to handle the request. Request and Org.apache.catalina.connector. The Response object. These two objects have been passed through the servlet container until they are passed to the servlet, which is the façade class Requestfacade and Requestfacade for the Request and Response, where the façade pattern is the same as before The purpose of the sample-encapsulating the data in the container. The class conversions for the corresponding request and Response are as follows:

Figure 8.Request and Response transformation process

How Servlets work

We already know how the servlet is loaded, how the servlet is initialized, and the architecture of the servlet, and now the question is how it is called.

When a user initiates a request from the browser to the server, it usually contains the following information: Http://hostname:port/contextpath/servletpath,hostname and Port are used to establish a TCP connection with the server, and the subsequent URL is the request to select the child container service user in the server. How is the server based on this URL to reach the correct Servlet container?

This is easy to solve in Tomcat7.0, because this mapping work has a special class to accomplish, this is org.apache.tomcat.util.http.mapper, this class holds Tomcat's Container Information about all the child containers in the container, when Org.apache.catalina.connector. Before the request class enters the Container container, Mapper will set the host and context containers to the Mappingdata attribute of the requests based on the Hostnane and ContextPath of the requested. So when the Request enters the Container container, it has to access the child container and it is determined.

Figure 9.Request Mapper class diagram

You may have questions about how the mapper has a complete relationship with the container, which goes back to the initialization of the 19-step Mapperlistener class in Figure 2, which is the Init method code for Mapperlistener:

Listing 5. Mapperlistener.init
public void init () {         finddefaulthost ();         Engine engine = (engine) connector.getservice (). GetContainer ();         Engine.addcontainerlistener (this);         container[] conhosts = Engine.findchildren ();         for (Container conhost:conhosts) {             host host = (host) conhost;             if (! LifecycleState.NEW.equals (Host.getstate ())) {                 Host.addlifecyclelistener (this);                 Registerhost (host);}}}  

The function of this code is to add the Mapperlistener class as a listener to each sub-container in the entire Container container, so that if any one container changes, Mapperlistener will be notified, the corresponding save container relationship The Mapper property of the Mapperlistener is also modified. The For loop is the registration of the host and the following sub-containers into mapper.

Figure 10.Request Routing diagram in a container

The diagram above depicts how the request request reached the final Wrapper container, and we are now aware of how the requests have reached the correct Wrapper container, but the request arrives at the final Servlet to complete some steps, the Filter chain must be executed, and to inform you of the Web The listener defined in the. Xml.

Next, the Servlet service method is executed, usually our own definition of the servlet is not directly to implement the Javax.servlet.servlet interface, but to inherit the simpler HttpServlet class or GENERICSE Rvlet class, we can choose to overwrite the corresponding method to achieve the work we want to accomplish.

The servlet has indeed been able to do all the work for us, but today's Web applications rarely use the servlet to directly interact with all of the pages, but instead use the more efficient MVC framework to implement them. The basic principle of these MVC frameworks is to map all requests to a Servlet and then implement the service method, which is the entrance to the MVC framework.

When the servlet is removed from the servlet container, it also indicates that the servlet's life cycle is over, and that the servlet's destroy method will be called to do some cleanup work.

"Servlet" Working principle analysis 2

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.