The start of the servlet container (tomcat as an example)

Source: Internet
Author: User
Tags addchild

I. Introduction to Containers

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

The Tomcat container model is as follows:

A context corresponding to a Web project, in the Tomcat configuration file Server.xml, you can find the configuration of the context (in the Eclipse Project, can be found in the Conf folder of the deployment path zhoing)

1 Context docbase= "/users/wongrobin/all/projects/tech-test/java-test/.metadata/.plugins/ Org.eclipse.wst.server.core/tmp0/wtpwebapps/base-webapp "path="/base-webapp "reloadable=" true "source=" Org.eclipse.jst.j2ee.server:base-webapp "/>  
Two. Start the servlet

Tomcat7 adds a startup class:

1

Create an instance object of Tomcat and invoke the Start method to start Tomcat.

This object can also be used to add and modify tomcat configuration parameters, such as the ability to dynamically increase context,servlet and so on.

In the example provided in TOMCAT7, see how it is added to the context container:

 1  Tomcat tomcat = Gettomcatinstance ();  2  file Appdir = new  file (  Getbuilddirectory (), "Webapps/examples" );  3  Tomcat.addwebapp (null , "/  Examples " 4  tomcat.start ();  5  bytechunk res = GETURL ("http://localhost:" + getport () + 6  "/examples/servlets/servlet/helloworldexample" );  7  asserttrue (res.tostring (). IndexOf ("

This code creates a Tomcat instance and adds a new web app, then launches Tomcat and invokes one of the Helloworldexampleservlet.

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

1  PublicContext Addwebapp (host host, string URL, string path) {2 silence (URL); 3Context CTX =NewStandardcontext (); 4 ctx.setpath (URL); 5 ctx.setdocbase (path); 6     if(Defaultrealm = =NULL) {  7 Initsimpleauth (); 8     }  9 Ctx.setrealm (Defaultrealm); TenCtx.addlifecyclelistener (NewDefaultwebxmllistener ());  OneContextconfig ctxcfg =NewContextconfig ();  A Ctx.addlifecyclelistener (CTXCFG);  -Ctxcfg.setdefaultwebxml ("Org/apache/catalin/startup/no_default_xml");  -     if(Host = =NULL) {   the gethost (). AddChild (CTX);  -}Else {   - Host.addchild (CTX);  -     }   +     returnCTX;  -}

A Web application corresponds to a context container, which is the servlet container for the servlet runtime. Adding a web App creates a Standardcontext container and sets the necessary parameters for the context container, and the URL and path represent the application's access path in Tomcat and the actual physical path of the application. These two parameters are consistent with the two parameters in the Tomcat configuration. One of the most important configurations is contextconfig, which is responsible for parsing the entire Web application configuration.
Finally, the context container is added to the parent container host.

The next call to Tomcat's Start method starts Tomcat.

Tomcat's startup logic is based on the observer pattern, and all containers inherit the Lifecycle interface, which manages the container's entire lifecycle, and all container modifications and state changes are notified to the registered observer.

The timing of Tomcat startup is as follows:

When the context container initial state is set to INIT, the listener added to the context container will be called. Contextconfig inherits the Lifecyclelistener interface, which is added to the Standardcontext container when Tomcat.addwebapp is called. The Contextconfig class is responsible for parsing the configuration files for the entire Web application.

The Init method of Contextconfig will do a major job:

    • Create a Contextdigester object for parsing an XML configuration file
    • Reads the default context.xml file and resolves it if it exists
    • Reads the default host configuration file and resolves it if it exists
    • Reads the default context's own configuration file and resolves it if it exists
    • Set the docbase of the context

When the Contextconfig init method is complete, the context container executes the Startinternal method, which includes the following sections:

    • To create an object that reads a resource file
    • Create a ClassLoader object
    • Set up your app's working directory
    • Start related auxiliary classes, such as logger,realm,resources, etc.
    • Modify the Startup status to notify interested observers
    • Initialization of a child container
    • Get ServletContext and set the necessary parameters
    • Initialize the servlet "load on Startuo"
Three. Initialization of Web applications

The initialization of Web application is implemented in the Configurestart method of Contextconfig, and the initialization of the application is mainly to parse the Web. xml file, which is the portal of a website application.

Tomcat will first find Globalwebxml, the search path for this file is the engine's working directory under Org/apache/catalina/startup/no-default_xml or Conf/web.xml. You will then find Hostwebxml, which 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,web.xml The individual configuration items in the file will be parsed into the corresponding properties stored in the Webxml object. Next, the properties in the Webxml object are set to the context container, including the creation of the Servlet object, Filter,listerner, etc., which are in the Webxml Configurecontext method.

Here is the code object that parses the servlet:

1  for(Servletdef servlet:servlets.values ()) {2Wrapper Wrapper =Context.createwrapper (); 3String Jspfile =Servlet.getjspfile (); 4     if(Jspfile! =NULL) {  5 Wrapper.setjspfile (Jspfile); 6     }  7     if(Servlet.getloadonstartup ()! =NULL) {  8 Wrapper.setloadonstartup (Servlet.getloadonstartup (). Intvalue ()); 9     }  Ten     if(servlet.getenabled ()! =NULL) {   One wrapper.setenabled (servlet.getenabled (). Booleanvalue ());  A     }   - Wrapper.setname (Servlet.getservletname ());  -map<string,string> params =Servlet.getparametermap ();  the      for(Entry<string, string>Entry:params.entrySet ()) {   - Wrapper.addinitparameter (Entry.getkey (), Entry.getvalue ());  -     }   - Wrapper.setrunas (Servlet.getrunas ());  +Set<securityroleref> rolerefs =servlet.getsecurityrolerefs ();  -      for(Securityroleref roleref:rolerefs) { + wrapper.addsecurityreference (Roleref.getname (), Roleref.getlink ());  A     }   at Wrapper.setservletclass (Servlet.getservletclass ());  -Multipartdef Multipartdef =servlet.getmultipartdef ();  -     if(Multipartdef! =NULL) {   -         if(Multipartdef.getmaxfilesize ()! =NULL&& -Multipartdef.getmaxrequestsize ()! =NULL&& -Multipartdef.getfilesizethreshold ()! =NULL) {   inWrapper.setmultipartconfigelement (NewMultipartconfigelement ( - multipartdef.getlocation (), to Long.parselong (Multipartdef.getmaxfilesize ()), + Long.parselong (Multipartdef.getmaxrequestsize ()), - Integer.parseint ( the Multipartdef.getfilesizethreshold ())));  *}Else {   $Wrapper.setmultipartconfigelement (NewMultipartconfigelement (Panax Notoginseng multipartdef.getlocation ()));  -         }   the     }   +     if(servlet.getasyncsupported ()! =NULL) {   A wrapper.setasyncsupported ( the servlet.getasyncsupported (). Booleanvalue ());  +     }   - Context.addchild (wrapper);  $}

The code above wraps the servlet container into a standardwrapper in the context container. Standardwrapper is part of the Tomcat container, it has the characteristics of the container, and the servlet, as a standalone web development standard, should not be forced to be coupled in Tomcat.

In addition to wrapping the servlet into standardwrapper and adding it as a child container to the context, all the other Web. XML properties are parsed into the context.

Four. Create a servlet instance

The servlet's parsing work was completed and was packaged as a standardwrapper added to the context container, but it still does not work for us, it has not yet been instantiated.

1. Create

If the servlet's Load-on-startup configuration entry is greater than 0, it is instantiated when the context container is started.

As mentioned earlier, the default globalwebxml is read when parsing the configuration file. Some default configuration items are defined in the Web. xml file under Conf, which defines two servlets, namely Org.apache.catalina.servlets.DefaultServlet and Org.apache.jsper.servlet.JspSe Rvelt, their load-on-startup are 1 and 3 respectively, which means that two servlets will be started when Tomcat starts.

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

2. Initialization

Initializing the servlet in Standardwrapper's Initservlet method, this method is very simple, called the servlet's init () method, At the same time, wrapping the Standardwrapper object's Standardwrapperfacade as ServletConfig to the servlet.

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

This completes the initialization of the Servlet object.

3. Container default servlet

Each servlet container has a default servlet, which is generally called default.

Example: Defaultservlet and Jspservlet in Tomcat (upper part)

The start of the servlet container (tomcat as an example)

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.