Servlet Working principle Analysis

Source: Internet
Author: User
Tags addchild apache tomcat

http://www.ibm.com/developerworks/cn/java/j-lo-servlet/

Speaking from the Servlet container

To introduce a servlet, you must first make the servlet container clear, and the servlet's relationship with the servlet container is a bit like the relationship between a gun and a bullet, the gun is born for bullets, and the bullet makes the gun lethal. Although they are interdependent, they develop independently of each other in order to adapt to the results of industrial production. From a technical point of view, to understand the decoupling, through standardized interfaces to collaborate with each other. Since interfaces are the key to connecting Servlets and servlet containers, let's start with their interfaces.

The front said the Servlet container as an independent development of standardized products, there are many kinds of it, but they have their own market positioning, it is difficult to say who gifted who inferior, each has characteristics. For example, now the more popular Jetty, in the field of customization and mobile has a good development, we are the most familiar with Tomcat as an example to describe how the servlet container management servlet. Tomcat itself is also very complex, we only start with the interface section of the servlet and servlet containers, and a detailed introduction to Tomcat can be found in one of my other articles, "Tomcat system architecture and pattern design analysis".

In the container hierarchy of Tomcat, the context container is the wrapper class Wrapper that directly manages the servlet in the container, so how the context container runs will directly affect the way the servlet works.

Figure 1. Tomcat Container Model

You can see that the Tomcat container is divided into four levels, the real management Servlet container is the context container, a context corresponding to a Web project, in the Tomcat configuration file can easily find this, as follows:

Listing 1 Context configuration parameters
<context path= "/projectone" docbase= "D:\projects\projectOne"  reloadable= "true"/>

The following is a detailed description of the process of Tomcat parsing the Context container, including how to build the Servlet.

The boot process for a Servlet container

TOMCAT7 also started to support embedded features, adding a startup class Org.apache.catalina.startup.Tomcat. Creating an instance object and invoking the Start method makes it easy to start Tomcat, which we can also use to add and modify tomcat configuration parameters, such as the ability to dynamically add Context, Servlet, and so on. Let's use this Tomcat class to manage the new context container, and we'll choose TOMCAT7 's own examples Web project and see how it's added to this context container.

Listing 2. Add a Web project to Tomcat
Tomcat tomcat = Gettomcatinstance ();  File Appdir = new file (Getbuilddirectory (), "webapps/examples");  Tomcat.addwebapp (NULL, "/examples", Appdir.getabsolutepath ());  Tomcat.start ();  Bytechunk res = GETURL ("http://localhost:" + getport () +                "/examples/servlets/servlet/helloworldexample");  Asserttrue (Res.tostring (). IndexOf ("

The code in Listing 1 is to create a Tomcat instance and add a new Web app, then start Tomcat and call one of the helloworldexample servlets to see if the expected data is returned correctly.

The code for Tomcat's Addwebapp method is as follows:

Listing 3. Tomcat.addwebapp
Public Context Addwebapp (host host, string URL, string path) {         silence (URL);         Context CTX = new Standardcontext ();         Ctx.setpath (URL);         Ctx.setdocbase (path);         if (Defaultrealm = = null) {             initsimpleauth ();         }         Ctx.setrealm (Defaultrealm);         Ctx.addlifecyclelistener (New Defaultwebxmllistener ());         Contextconfig ctxcfg = new Contextconfig ();         Ctx.addlifecyclelistener (ctxcfg);         Ctxcfg.setdefaultwebxml ("Org/apache/catalin/startup/no_default_xml");         if (host = = null) {             gethost (). AddChild (CTX);         } else {             host.addchild (CTX);         }         return CTX;  }

A Web application corresponding to a context container, which is the servlet container of the servlet runtime, is described earlier, a Standardcontext container is created when a Web application is added, and the necessary parameters are set for the context container. The URL and path represent the application's access path in Tomcat and the actual physical path of the application, which is consistent with the two parameters in Listing 1. One of the most important configurations is contextconfig, which will be responsible for parsing the entire WEB application configuration, which will be described in more detail later. Finally, the Context container is added to the parent container Host.

Then the tomcat Start method will be invoked to launch Tomcat, and if you know Tomcat's system architecture, you will easily understand Tomcat's startup logic, and Tomcat's boot logic is designed based on the observer pattern, and all containers inherit the Lifecycle interface, which The entire life cycle of the manager's container, the modification of all containers and the change of state will be notified to the registered observer (Listener), and the design pattern can refer to Tomcat's system architecture and design patterns, Part II: Design Patterns. The sequence diagram that Tomcat launches can be shown in Figure 2.

Figure 2. Start sequence diagram for Tomcat main class (View larger image)

Describes the timing relationships between major classes during Tomcat startup, and below we will focus on the start-up process for adding the Standardcontext container corresponding to the examples application.

When the Context container initialization state is set to INIT, the Listener added to the Contex container will be called. Contextconfig inherits the Lifecyclelistener interface, which is added to the Standardcontext container in the call Listing 3 o'clock. The Contextconfig class is responsible for parsing the configuration files for the entire WEB application.

The Init method of Contextconfig will mainly do the following:

    1. Create a Contextdigester object for parsing an XML configuration file
    2. Reads the default context.xml configuration file if it exists to resolve it
    3. Reads the default Host configuration file if it exists to resolve it
    4. Reads the default Context itself configuration file if it exists to parse it
    5. Set the DocBase of the Context

After the Contextconfig init method is complete, the Context container executes the Startinternal method, which is more complex to start the logic, including the following parts:

    1. To create an object that reads a resource file
    2. Create a ClassLoader object
    3. Set up your app's working directory
    4. Start related auxiliary classes such as: logger, realm, resources, etc.
    5. Modify the Startup status to notify the viewer of interest (Web app configuration)
    6. Initialization of a child container
    7. Get ServletContext and set the necessary parameters
    8. Initialize the Servlet for "load on startup"
Initialization of WEB applications

The initialization of Web applications is implemented in the Configurestart method of Contextconfig, where the initialization of the application is primarily to parse the Web. xml file, which describes the key information of a website application and the portal of a Web application.

Tomcat will first find Globalwebxml. The search path for this file is in the engine's working directory looking for any of the following two files in either Org/apache/catalin/startup/no_default_xml or conf/ Xml. Then we'll find Hostwebxml. This file may be in System.getproperty ("Catalina.base")/conf/${enginename}/${hostname}/ Web.xml.default, then look for the application configuration file Examples/web-inf/web.xml. Each configuration item in the Web. xml file will be parsed into the corresponding attribute saved in the Webxml object. If the current app supports Servlet3.0, parsing will also complete an additional 9 jobs, and this additional 9 work is primarily for Servlet3.0 new features, including parsing of meta-inf/web-fragment.xml in jar packages and annotation S's support.

Next, you will set the properties in the Webxml object to the context container, which includes creating the Servlet object, filter, listener, and so on. This code is in the Configurecontext method of Webxml. Here is the code snippet to parse the Servlet:

Listing 4. Creating an Wrapper instance
 For (Servletdef servlet:servlets.values ()) {Wrapper Wrapper = Context.createwrapper ();             String jspfile = Servlet.getjspfile ();             if (jspfile! = null) {wrapper.setjspfile (jspfile); } if (servlet.getloadonstartup () = null) {Wrapper.setloadonstartup (Servlet.getloadonstartup (             ). Intvalue ());              } if (servlet.getenabled () = null) {wrapper.setenabled (servlet.getenabled (). Booleanvalue ());             } wrapper.setname (Servlet.getservletname ());             map<string,string> params = Servlet.getparametermap (); For (entry<string, string> entry:params.entrySet ()) {Wrapper.addinitparameter (Entry.getkey (), ENT             Ry.getvalue ());             } Wrapper.setrunas (Servlet.getrunas ());             set<securityroleref> rolerefs = Servlet.getsecurityrolerefs (); for (Securityroleref Roleref:roLerefs) {wrapper.addsecurityreference (Roleref.getname (), Roleref.getlink ());             } wrapper.setservletclass (Servlet.getservletclass ());             Multipartdef multipartdef = Servlet.getmultipartdef (); if (multipartdef! = null) {if (multipartdef.getmaxfilesize ()! = null && m                     Ultipartdef.getmaxrequestsize ()! = null && multipartdef.getfilesizethreshold ()! = null) { Wrapper.setmultipartconfigelement (New Multipartconfigelement (multipartdef . GetLocation (), Long.parselong (Multipartdef.getmaxfilesize ()), Lon                                     G.parselong (Multipartdef.getmaxrequestsize ()), Integer.parseint (                 Multipartdef.getfilesizethreshold ()))); } else {Wrapper.setmultipartcoNfigelement (New Multipartconfigelement (Multipartdef.getlocation ()));                         }} if (servlet.getasyncsupported () = null) {wrapper.setasyncsupported (             Servlet.getasyncsupported (). Booleanvalue ());  } context.addchild (wrapper); }

This code clearly describes how to wrap a servlet into a standardwrapper in a Context container, where there is a question as to why the servlet is packaged as a standardwrapper rather than a Servlet object. Here Standardwrapper is part of the Tomcat container, it has the characteristics of the container, and the Servlet should not be strongly coupled in Tomcat for a standalone web development standard.

In addition to wrapping the servlet into a standardwrapper and adding it as a child container to the context, all the other Web. XML properties are parsed into the context, so that the context container is the servlet that really runs the servlet Container. A WEB application corresponds to a Context container, and the configuration properties of the container are specified by the application's Web. XML, so that we can understand exactly what web. XML works.

Back to top of page

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 defaults are defined in the Web. xml file under CONF. Definition of two servlets, namely: Org.apache.catalina.servlets.DefaultServlet and Org.apache.jasper.servlet.JspServlet of 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. To create a related class structure for a Servlet object initialize a 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 Standardwrapperf Acade 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 listener events caused by conversions of various container states, The control of various access rights and the judging behavior of some unpredictable errors occur, 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 (see larger image)

Back to top of page

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

It can be seen 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

is the 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

Back to top of page

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

Describes how the request request reaches the final Wrapper container, and we are now aware of how requests reach the correct Wrapper container, but the request arrives at the final Servlet to complete some steps, the Filter chain must be executed, and you are notified of the web.x The listener defined in ML.

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.

Back to top of page

Session and Cookie

We have already explained how the servlet is invoked, and we build the application based on the servlet, so what data information can we get from the servlet?

The servlet can provide us with two pieces of data, a servletconfig that is set when the Init method is called when the servlet is initialized, which basically contains the basic information in the servlet itself and the servlet container that the servlet runs. According to the previous introduction of the actual object of the ServletConfig is Standardwrapperfacade, in the end can get what container information can see what this kind of interface provided. A subset of the data is provided by the ServletRequest class, and its actual object is Requestfacade, which is found primarily in the information provided by the HTTP protocol that describes the request. So to master the Servlet's way of working must be clear about the HTTP protocol, if you are not sure to hurry to find some resources. There is also a Session and Cookie that confuses many people about this piece.

Sessions and cookies are a headache for both skilled users of the Java Web and for beginners. Both sessions and cookies are designed to keep access to the user's interaction with the backend server. They have their own merits as well as their own flaws. Ironically, however, their merits and their use of the scene are contradictory, such as the use of cookies to convey information, as the number of cookies and traffic increases, it occupies a large network bandwidth, imagine if the cookie occupies 200 bytes, if the day of PV hundreds of millions of , how much bandwidth it consumes. So when the large number of visits to the session, but the fatal weakness of the session is not easy to share among multiple servers, so this also limits the use of the session.

No matter what the Session and Cookie are, we'll use them. Let's talk about how the Session works based on cookies. There are actually three ways to make the Session work:

    1. URL-based Path Parameter, which is supported by default
    2. Based on cookies, if you do not modify the Context container cookie logo, it is supported by default
    3. SSL-based, not supported by default, only supported if Connector.getattribute ("Sslenabled") is true

In the first case, when the browser does not support the Cookie feature, the browser overrides the user's sessioncookiename to the URL parameter of the user request, and its delivery format is/path/servlet;name=value;name2=value2. Name3=value3, where "Servlet;" The k-v pair is the path Parameters to be passed, the server gets the sessioncookiename of the user configuration from this path Parameters. Regarding this sessioncookiename, if you configure the Session-config configuration item in Web. XML, the Name property under its cookie-config is the Sessioncookiename value, if you do not configure SE Ssion-config configuration items, the default sessioncookiename is the familiar "Jsessionid". The Request then gets the Session ID from the Sessioncookiename to Parameters and sets it to Request.setrequestedsessionid.

Please note that if the client also supports cookies, Tomcat will still parse the session ID in the cookie and overwrite the session ID in the URL.

If it is a third case, the session ID will be set according to the Javax.servlet.request.ssl_session attribute value.

With the Session ID server, you can create a HttpSession object, and the first trigger is via request. GetSession () method, if the current Session ID does not have a corresponding HttpSession object then create a new one and add the object to Org.apache.catalina. Manager's sessions container, the manager class will manage the lifetime of all sessions, the session expiration will be recycled, the server shuts down, the session will be serialized to disk, and so on. As long as this HttpSession object exists, the user can get to this object according to the Session ID, and the state is maintained.

Figure 11.Session Related class diagram

It can be seen that the HttpSession object obtained from Request.getsession is actually the façade object of the Standardsession object, which is the same principle as the previous request and Servlet. Is the sequence diagram of the Session work:

Figure 12.Session Timing Diagram of work (view larger image)

There is also a point that the cookie associated with the Session is not the same as other cookies, and this configuration can be specified through the Session-config configuration item in Web. Xml.

Back to top of page

Listener in a Servlet

Listener is used extensively throughout the TOMCAT server, it is based on the observer pattern design, and the Listener design provides a quick way to develop a Servlet application that facilitates the control of the program and data from another longitudinal dimension. Currently, there are 5 observer interfaces for two types of events in the Servlet: 4 eventlisteners types, Servletcontextattributelistener, Servletrequestattributelistener, Servletrequestlistener, Httpsessionattributelistener, and 2 LifecycleListeners types, Servletcontextlistener, Httpsessionlistener. As shown in the following:

Listener in Figure 13.Servlet (view larger image)

They basically cover every kind of event that you're interested in throughout the Servlet life cycle. The implementation classes of these Listener can be configured in the <listener> tag in Web. Xml. It is also possible to add Listener dynamically in the application, noting that Servletcontextlistener cannot add new after the container has been started, because the events it listens on are no longer present. Mastering the use of these Listener can make our program design more flexible.

Back to top of page

Summarize

This article involves a bit more content, to make every detail clear, it seems impossible, this article tries to start from the servlet container to the initialization of the servlet, and the servlet architecture and other aspects of these links to find out some of the key points to tell, the purpose is to be able to have a complete picture of the overall structure of the reader, At the same time also detailed analysis of some of the difficult issues, I hope to help you.

Reference Learning
    • View the article "Tomcat system architecture and Design Patterns" (developerworks,2010 May): Learn about the architecture of the container in Tomcat, how it works, and the classic design patterns that are used in Tomcat.
    • Java servlet Technology Brief (developerworks,2004 December): Describes and explains what Servlets are, how they work, how to use them to create any complexity you can imagine Web applications, and as a professional programmer, How you can most effectively use Servlets.
    • Refer to the Apache Tomcat website for the latest Tomcat updates and developer reference manuals.
    • The latest servlet specification, this article is based on the SERVLET3.0 specification, here are the latest servlet specifications, as well as an introduction to the API.
    • HTTP protocol, a detailed description of the HTTP protocol.
    • DeveloperWorks Web Development Zone: Extend your skills in web development with articles and tutorials dedicated to web technology.
    • DeveloperWorks Ajax Resource Center: This is a one-stop center for information about AJAX programming models, including many documents, tutorials, forums, blogs, wikis, and news. Any new Ajax information can be found here.
    • The DeveloperWorks Web 2.0 Resource Center, a one-stop Center for Web 2.0-related information, includes a large number of Web 2.0 technical articles, tutorials, downloads, and related technical resources. You can also quickly learn about the concepts of Web 2.0 through the Web 2.0 starter section.
    • Check out the HTML5 topic for more information and trends related to HTML5.

Servlet Working principle Analysis

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.