TOMCAT Source Analysis (start frame)

Reprinted: **edu.codepub**/2010/0518/22773.php

TOMCAT Source Analysis (start frame)
This is after I read some tips TOMCAT source. Mainly explain the TOMCAT system framework, and start the process. If errors and omissions, please criticize advice!
After all, the framework of the TOMCAT is quite complicated, it is understood from the text, it is not so easy to master TOMCAT framework. So was practice, practice, more practice. Recommend to download a TOMCAT's source code, debugging through, and then track its startup process step. If there do not understand, again access to this article to see if can be helped. I believe this effect and the learning speed will be much better!
1. Tomcat overall frame structure
Tomcat's basic framework, divided into 4 levels.
Top Level Elements:
Standing on top of the framework is the Server and Service
Server: actually BackGroud procedures inside the Server in the Tomcat startup and monitor the usefulness of a server-side events (such as restart, shut down and other commands. The standard configuration file in tomcat: server.xml inside, we can see ";" here "SHUTDOWN" is the server-side events in the monitoring service is used when the command word)
Service: In tomcat inside, service is a class of solutions to problems. Usually we will default tomcat provided: Tomcat-Standalone mode service. In this way the service not only provides us with analytical jsp and servlet services, but also provide us with a static text parsing services.
Connector: Tomcat is a container which deal with the problem, but where to get the container they enter information?
Connector is specifically doing that for. He would pass over the data from the socket, packaged Request, passed to the container to handle.
Usually we will use two Connector, something called http connectoer, to pass http demand. Another called the AJP, integrating apache and tomcat in our work, when, apache and tomcat is through this agreement between the interaction. (Speaking of apache and tomcat integration efforts, usually the purpose is to allow apache access to static resources, and allow tomcat to parse the dynamic jsp or servlet.)
Container: When the http connector to demand transfer to the top of the container: Engin, we should move to the sight of this dimension to the Container.
In the Container of this layer, we include three kinds of containers: Engin, Host, Context.
Engin: come before the needs of service delivery, treatment, the results returned to the service (service is the medium through the connector to and Engin interaction).
Host: Engin receive service delivered over the needs, not their treatment, but to the appropriate Host to handle.
Host here is the meaning of the virtual host, usually we will only use a host, not only "localhost" to address the local machine.
Context: Host Host Communication received came from the demand, and will not deal with their own, but to the appropriate Context to handle.
For example:;
The former deal over foo in this Context, the latter handed over to bar the Context handle.
Obviously it! context of meaning is in fact the meaning of a web app.
We usually do this in the server.xml configuration inside
The context container that is used to dry our thing in the dry places.
Compenent: Next, we continue to talk about what component is used.
We must first understand how the relationship between the container and components.
Needs to be passed to the container which, at the right time, will be passed to the next container handling.
The vessel which they dress a variety of components, we can be understood as a wide range of value-added services.
manager: When a manager component installed inside the container after the container to support the session management, and in fact inside the tomcat session management in the context which is installed by the manager component.
logger: When a logger component installed inside the container after the container what happened, it was the component recorded it! We usually logs / this directory to see catalina_log.time.txt and localhost.time.txt and localhost_examples_log.time.txt. This is because we were: engin, host and context (examples) of these three containers installed logger component, which is installed by default, also known as standard:)
loader: loader of this component is usually only given us the context container use, loader is used to start the context and the management of the context of the classloader used.
pipline: pipeline is the thing that determines when a container should be passed from parent to child over the needs of the container, he took this demand into the container pipe (pipeline) to go inside. The demand insensibly get inside the pipe flow when the pipe which will be blocked off all the valves. Such as pipe inside with two valves. The first valve is called "access_allow_vavle", means that demand for flow over time, it will see what the demand is over IP, and if this IP is already inside a black, sure, kill! The second valve is called "defaul_access_valve" It will do routine checks, if adopted, OK, the demand for container is passed to the current sub-containers. Is through this way, the demand for containers in which each transfer, flow, and finally arrived at the destination.
valve: the valve is the Rights described above.
Tomcat is probably these many things inside, so we can easily understand the framework of tomcat, it is a top-down, container also contains sub-containers of such a structure.
2. Tomcat startup process This article is about how to start tomcat, since we generally understand the TOMCAT of the frame structure, then we can expect the text to guess the business to start tomcat will start before the parent container, and then one by one start inside the sub-containers. Start time of each container will start the placement of components on him. When all the components started finished, start all the containers when finished, tomcat itself also started finished.
A matter of course, we can also guess, tomcat startup will be divided into two parts, the first step is assembly. The second step is to start work.
Assembly is installed on the parent container sub-containers, each container is inserted into the components of the work safety. This place we will use digester model, as for what digester model, what's the use, how to work. Please refer to;
Start work after working in the assembly, once the assembly is successful, we need only light the top one wire, the tomcat will be activated together. This is like we have assembled to drive a car when the same as long as we have the key inserted into the key hole, a screw, the car engine will be mobilized, it will open up air-conditioning, safety devices will come into effect In this way, the whole car up on the launch. (This process does and TOMCAT startup process does not seek and and so we have to suspect that the designer is TOMCAT JAVA development in the GE to do).
2.1 Some interesting names:
Their meaning is very interesting:
Catalina: long-range bombers
Tomcat: Panda bombers - A bomber (which reminds me of their countrymen proud panda phone is not in English can be called a tomcat???, Let me think of another ad: Bird - phone fighter aircraft, Boeing - the fighter aircraft)
Bootstap: guide
Engin: Engine
Host: host, territory
Context: the content, objectives, context
... In many many years later, modern humans have become extinct. After these words of modern biotechnology found scattered scattered in a. A smart guy from that translation out of these things:
Guidance in the ground crew (bootstrap), the one bomb rack (catalina) vacated leaps, a distance is the panda bombers (tomcat), the last to see the panda or the bombers! With excellent engine technology (engin), this aircraft Panda bombers flew over the enemy's territory (host), at the target (context) day off to cast a destroyed nuclear warheads, such a wave ~ modern biotechnology separated on a fart ~
In summary, this has compelled people to think of GE is not also involved in military equipment production?
Opposition to U.S. imperialism! Against U.S. hegemony! Long live peace! Long live freedom!
2.2 The history is so surprisingly similar! tomcat startup is blatant from org.apache.catalina.startup.Bootstrap the class started!
In the Bootstrap in doing two things:
1. Specifies 3 types of classloader:
commonLoader: common / classes, common / lib, common / endorsed
catalinaLoader: server / classes, server / lib, commonLoader
sharedLoader: shared / classes, shared / lib, commonLoader
2. Guiding Catalina startup.
Using Reflection technology called org.apache.catalina.startup.Catalina the process method, and pass parameters in the past.
Catalina completed several important tasks:
1. Digester technology used in various containers and component assembly tomcat.
1.1 The main elements of assembly is installed in all large. For example, under what kind of server servcie. Host will accommodate the number of context. Context will use to which components and so on.
1.2 at the same time, this step in the assembly, also completed the configuration mbeans. Here, I briefly, but not very accurately describe the mbean what do use.
The object of our own generation, their management, natural! But if we create the object, and want someone else to manage, how do? I would like to at least tell people what we have and by what methods can be found it! JMX technology provides a means for us. JMX There are three kinds of things inside. Mbean, agent, connector.
Mbean: used to map our objects. Perhaps the mbean that we create an object, maybe not, but with it, it can refer to our object.
Agent: through it, you can find the mbean has.
Connector: Connection Agent approach. Can be http, and it can be rmi, and also directly through socket.
Tomcat in the assembly process in a matter: GlobalResourcesLifecycleListener class initialization will be triggered:
protected static Registry registry = MBeanUtils.createRegistry (); will run
MBeanUtils.createRegistry () will be based / org / apache / catalina / mbeans / mbeans-descriptors.xml this configuration file to create mbeans. Ok, there will be ways to access the outside world in the various components of a tomcat. (A bit like the back door child)
2. For the top level of the server to do the initial work. Actually do is usually configured to service two connector. (Http, ajp)
3. From the server that the container started to light the whole tomcat.
4. For the server to do a hook procedure to detect when the server shutdown time, shut down all containers with tomcat.
5. Listening 8005 port, if you send "SHUTDOWN" (default cultivate the next string) over, close 8005serverSocket.
2.4 Start each container
1. Server
Trigger Server container before the start (before_start), start in the (start), starts (after_start) 3 incidents, and run the appropriate event handler.
Start Server sub-containers: Servcie.
2. Service
Start Service in the sub-containers: Engin
Start Connector
3. Engin
Engin to this level, and the following levels of container, Tomcat on the use of a more consistent way of a start.
First, run a number of tasks in various containers own unique then trigger the event immediately before the start, set the label, it means that the container has been launched and then, start the container in the various components: loader, logger, manager, etc. Then again, start mapping component . (Note 1)
Followed, promoter container.
Next, start the container of the pipeline (pipline)
Then, the trigger events in the last start, triggering the event starts.
Engin less will do, Host or less will do, Context generally still do. So obviously, we need to use here the technology to code reuse. tomcat in dealing with this problem, beautiful use of the abstract class to handle. ContainerBase. Finally make this part of the complex functions of the code completion appears crisp, capable straightforward, it is really that amazing, thin products to, enjoy good intuition as Jane, the other one cheek teeth, your mouth, nostalgia from ah!
Engin before the start of the event where the trigger will be activated only on binding in Engin a Listener: EnginConfig.
This EnginConfig class basically do anything, is to set the debug level EnginConfig and Engin quite. The other is the output of a few lines of text, that Engin are configured and what not to do substantive work.
Note 1: mapping components of the use is that when a demand from the parent container when the container is passed to the child, but there are multiple sub-containers parent container, then the container should choose which child to deal with demand? The final decision by the mapping component.
4. Host
As with Engin is called ContainerBase inside start () method, but made some myself before the task is to Host the container channel (pipline) inside, the installation of a called "org.apache.catalina.valves.ErrorReportValve "valve.
Usefulness of this valve is this: the demand is passed to the Host Engin, will continue to do so passed to the Context specific treatment. Here the demand is actually passed as a parameter of Request, Response. Therefore, the demand has been dealt with in the context usually change response. The role of this org.apache.catalina.valves.ErrorReportValve is whether the prosecution response contains an error, if there is to do the appropriate treatment.
5. Context
To here, on the last turn of the tomcat start in the real main event, start a Context.
StandardContext.start () The startup method is StandardHost Context container call.
5.1 webappResources the context points to a specific directory
5.2 Installation defaultContex, DefaultContext is the default Context. If we installed the following in a Host DefaultContext, and defaultContext which has installed a database connection pool resources to do so. Then all the other under the Host Context, can directly use the database connection pool, but do not particularly configured.
5.3 specify the Loader. Usually the default org.apache.catalina.loader.WebappLoader this class. Loader is used to specify which classes will be used in this context, ah, ah those which jar package or something.
5.4 The designated Manager. Usually use the default org.apache.catalina.session. StandardManager. Manager is used to manage the session's.
In fact, the management is also very good session to achieve. Session management in a simple example. When the demand for transmission over time, in the Request object inside a sessionId attribute. OK, get this sessionId, we can map it as the key, and the value we place a HashMap. HashMap children inside, add the things we want to put.
5.5 postWorkDirectory (). Tomcat following a work directory. We are the temporary files are left in there too. This step is to create a directory in there. Generally speaking, in the% CATALINA_HOME% / work / Standalone \ localhost \ this place to generate a directory.
5.6 Binding thread. To where it should happen class Loader exchanged. Tomcat visible until all the class and the following lib. The next step is visible under the current context class. So to set the contextClassLoader, while also recording the old ClassLoader, because we still use.
5.7 start the Loader. Specify what you want to use the Context of specific classes, use which jar file. If reloadable set to true, will start a thread to monitor changes in classes, if there are changes on restart Context.
5.8 start the logger
5.9 installed on it to trigger a listener.
lifecycle.fireLifecycleEvent (START_EVENT, null);
As one listener, ContextConfig will be started. ContextConfig is used to configure the web.xml for. Context such as the number of Servlet, how many Filter, is here to put something in Context.
5.9.1 defaultConfig. Each context had to configure the tomcat / conf / web.xml to this file.
5.9.2 applicationConfig configure your WEB-INF/web.xml file
5.9.3 validateSecurityRoles permissions validation. Usually we visit / admin or / manager when the user either needs to either admin manager, and to access. And we also can limit access to those resources, and which can not. Here are achieved.
5.9.4 tldScan: scan about the need to use what label (tag lab)
5.10 Startup manager
5.11 postWelcomeFiles () we would normally use the three boot file name:
index.html, index.htm, index.jsp tied on by default in this context on
5.12 listenerStart configuration listener
5.13 filterStart configuration filter
5.14 start with; 1; the Servlet.
Order is from small to large: 1,2,3 ... and finally 0
By default, start at least the following three of the Servlet:
Deal with static resources Servlet. What pictures ah, html ah, css ah, js ah are looking for him
Deal not done Servlet Mapping those Servlet.
Processing JSP file.
5.15 identify context has started finished.
How many steps to go ah, Context is finally finished woven start.
OK! Come here, start each container as well as finished components. Tomcat finally tirelessly serving the people of the!
3. References:
4. Postscript tomcat start of this article is to explain the framework, there are articles explaining the TOMCAT inside details of message handling process. Article content is written, and now is finishing stage. Will soon be able to do it and common of common progress.
This article was written independently of TOMCAT source, so there must be places with a personal subjective, inevitably there will be one-sided between. If inappropriate please teach critical, not only allows the beginning of TOMCAT brothers avoid detours, I can learn something.
5. Tomcat source code analysis (information processing)

-------------------------------------------------- -----------------

0: Introduction We know that the overall framework of the tomcat, and also understand what components are inside, and what each component is used in the.
I would like, then we should look into is how to deal with tomcat jsp and servlet requests.
1. We are a concrete example, to track TOMCAT, to see how it is to submit a Request to the next level by level in a container, and finally to the Wrapper to handle.
To **localhost:8080/web/login.jsp as an example (the following examples are based on tomcat4 source as a reference)
This experience is divided into three parts: early, mid, and late.
Previous: explained inside the browser to enter a URL, how he has been caught tomcat.
Medium: talk of being caught and tomcat, but also how the various containers inside the shuttle, and finally to the final disposal sites.
Final: explain the place of arrival, after the last treatment, but also how specifically to deal with.
2, pre-Request for born.
Here, I briefly talk about this stuff request.
We first looked at this URL: **localhost:8080/web/login.jsp it is to use the 8080 port for socket communications.
We know, through the
InputStream in = socket.getInputStream () and
OutputStream out = socket.getOutputStream ()
Messages can be achieved has come and go.
However, if the Stream to the application layer, it is clear operation inconvenient.
Therefore, the Connector in tomcat inside, socket is encapsulated into two objects Request and Response.
We can simply Request as control data sent to the server, the Response as to send the server data.
But there are other problems that ah? Request this object is to encapsulate the socket, but he has provided many things.
Such as Request.getAuthorization (), Request.getSocket (). Authorization of such things as developers are basically brought forward with less, but such things as socket, exposed to developers as well as potential dangers. And ah, in the Servlet Specification which is a standard communication class ServletRequest and HttpServletRequest, instead of the Request class. So, So, So. Tomcat have to trace and hold trace and hold Request Caixing. Finally tomcat who chose to use trace mode (should be called the adapter mode) to solve this problem. It became the org.apache.catalina.Request trace and hold org.apache.coyote.tomcat4.CoyoteRequest. The CoyoteRequest ServletRequest and HttpServletRequest they realized the two interfaces. This will provide developers need and just need a way to go.
ok, let us in on top of tomcat container - StandardEngin the invoke () method to set a breakpoint here, then visit
**localhost:8080/web/login.jsp, we will look at passing in front where:
1. Run (): 536, java.lang.Thread,
2. Run (): 666, org.apache.tomcat.util.threads.ThreadPool $ ControlRunnable,
3. RunIt (): 589, org.apache.tomcat.util**.TcpWorkerThread,
4. ProcessConnection (): 549
org.apache.coyote.http11.Http11Protocol $ Http11ConnectionHandler,
http protocol parser
5. Process (): 781, org.apache.coyote.http11.Http11Processor,
http request processor
6. Service (): 193, org.apache.coyote.tomcat4.CoyoteAdapter,
7. Invoke (): 995, org.apache.catalina.core.ContainerBase,
1. The main thread
2. Start the thread pool.
3. Redeployment inside the idle thread pool of worker threads.
4. To pass over from the httpd port 8080 protocol encapsulated data, Request and Response objects resolves.
5. Use Http11Processor to handle request
6. Http11Processor inside, will be fit to handle call CoyoteAdapter to fit into the implementation of the ServletRequest Request and HttpServletRequest interface CoyoteRequest.
7. To here early to work on basically the skin hair pulling it out, you can do to StandardEngin core processing work.
3. Medium. Shuttle between the various containers.
Request a shuttle inside the various containers are generally in such a way:
Inside each container has a pipe (pipline), designed to send a Request used.
Inside there are several pipeline valve (valve), designed to filter Request used.
The lower part of the pipeline usually put a default valve. This valve will do one thing at least, is the Request to the sub-containers.
Let us imagine:
When a Request into a container, it flows inside the pipe, the Baltic ~ Baltic ~ Baltic ~ across all valves. Flow valve in the last time, Ba Ji ~ that damn valve put it threw the child container. Then began the Baltic ~ Baltic ~ Baltic ~ ... Baji ~.... ~ Polo Polo Polo ~ ~ .... Baji ~....
Is through this way, Request has completed all of the containers. (Feel a bit like the digestive system, somewhat like the last place where the ~)
OK, let us all see what the specific container, all containers which are both what the valve, these valves have all done it on our Request:
3.1 StandardEngin put inside the pipeline is: StandardEnginValve
Here, VALVE to do three things:
1. Verify pass over the request is not httpservletRequest.
2 verify the transfer request is carried over the host header information.
3 Select the appropriate host to deal with it. (General we have only one host: localhost, which is
To this place, our request to have completed this part of the historic mission in Engin, leading to uncertainty of the next stop: host a.
3.2 StandardHost the pipline is put inside: StandardHostValve
1. Verify pass over the request is not httpservletRequest.
2. According to Request to determine which Context to deal with.
Context is actually webapp, for example **localhost:8080/web/login.jsp
Context here is Luo web!
3. Since the set is which Context, and then it should be paid to the Context of the classloader of the current thread.
Thread.currentThread (). SetContextClassLoader (context.getLoader (). GetClassLoader ());
This request will only see the following classes context specified ah, jar ah these, but can not see tomcat's own class, what Engin ah, Valve ah. Otherwise have to, ah!
4. Since the request to here, it seems the user is ready to visit the web the web app, and ye have to update their look at the user's session is not! Ok, by the manager to update the information about the user's session
5. To the specific container to remain seized of the Context Request.
6. Context disposed of, and the classloader to come back.
3.3 StandardContext the pipline is put inside: StandardContextValve
1. Verify pass over the request is not httpservletRequest.
2. If the request ill intent, you want to visit / meta-inf, / web-inf directory of these things, huh, huh, do not use the D!
3. This time in the end will be according to Request Servlet, or jsp, or the static resources to decide in the end Wrapper with which to deal with this Reqeust the.
4. Once decided in the end, in what Wrapper, OK, to address the Wrapper.
4. Late. How the different needs treatment.
Wrapper not done before the talks, the fact that it is such a thing.
Request a time when we deal with can be divided into three kinds.
Handling static: org.apache.catalina.servlets.DefaultServlet
Handle jsp's: org.apache.jasper.servlet.JspServlet
Processing servlet's: org.apache.catalina.servlets.InvokerServlet
Different with this request on 3 different servlet to handle.
Wrapper is a simple on their packaging, with the Wrapper, we can easily block each Request. Also can easily call the servlet's init () and destroy () method, easy to manage it!
Situation is so drops:
If the request is to find jsp file, StandardWrapper will be packaged inside a org.apache.jasper.servlet.JspServlet to deal with it.
If the request is to find static resource, StandardWrapper will be packaged inside a org.apache.jasper.servlet.DefaultServlet to deal with it.
If the request is to find servlet, StandardWrapper will be packaged inside a org.apache.jasper.servlet.InvokerServlet to deal with it.
StandardWrapper is also container, since it is the container, then there must remain a pipe to a request to wear, certainly the lower part of pipe has a valve (1), to finally work together to intercept.
In the bottom of the valve, the fact will mainly do two things:
First, start the filter, so that request in the N-pass filter inside a sieve, if OK! Then PASS. Otherwise, skip the rest go.
Second, servlet.service ((HttpServletRequest) request, (HttpServletResponse) response); this method.
If JspServlet, then the first jsp file compiled servlet_**, and then invoke servlet_** the servie () method.
If DefaultServlet, static resources directly to find, remove content, send out.
If InvokerServlet, to call that specific servlet's service () method.
ok! completed.
Note 1: StandardWrapper inside the valve is the last one pass. If the valve StandardWrapper wanting to request a sub-containers to handle. Sorry, when considered in the design, Wrapper will be considered as Last of a container, simply did not add a sub-containers will give the opportunity Wrapper! If obstinately to call addChild (), flew throw IllegalArgumentException!
标签: source code, configuration file, errors and omissions, service server, server side, debugging, frame structure, system framework, server service, source analysis, static text, level elements, monitoring service, service connector, word service, component manager, command word
分类: Java
时间: 2010-09-11


  1. liferay portal 5.23 tomcat Source analysis of the load configuration files <2>

    In the listener PortalContextLoaderListener call contextInitialized () method after. Go add context parameters ...
  2. TOMCAT source code analysis (Message Processing)

    TOMCAT source code analysis (Message Processing)
  3. Axis source analysis - the server processes the request and response (3)

    Source analysis of the Axis-Web Services Deployment (II) Has two we ...
  4. Tomcat source code of a full request ------

    Tomcat source code analysis (II )------ ins and outs of a complete collection of a few days before the request ...
  5. <Switch> To get more from the Tomcat source code analysis-Tomcat

    Description: This article by TomCat source code of the study described to the reader in the tomcat3.3 and TomC ...
  6. Tomcat source research - (a) source code to compile and import MyEclipse6.0

    Graduation is six months, and feel very lazy day of work, technically there is no progress, in order to superv ...
  7. tomcat Code Analysis

    Since the blog launched last year, after the article was never written, the next it is very ashamed ah, which ...
  8. tomcat source code installation and commissioning (1)

    References: ...
  9. Struts1 Source analysis - international resource file

    Struts1 Source analysis - international resource file 1. URL class diagram 2. Description a) Struts resources ...
  10. tomcat source of the Observer pattern and the application of load - Lifecycle

    Studied the tomcat source may have found friends, tomcat component of several major Lifecycle interfaces are i ...
  11. HashMap source analysis

    HashMap source analysis public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V&g ...
  12. Lucene3.0 Source Analysis (1) in the Eclipse / MyEclipse project to build Lucene3.0

    Source analysis of the first step is to establish related projects in the IDE, and then go step by step learni ...
  13. tomcat structure analysis

    Tomcat is a component-based server, which constitute the components are configurable, the most outer layer of ...
  14. CLucene source analysis (c) cross-platform, thread-safe

    Home> CLucene, program Life> CLucene source analysis (c) cross-platform, thread-safe CLucene source anal ...
  15. tomcat source learning - the thread pool

    Write a foreword: Usually we know the tomcat thread pool can be configured to find the following in the server ...
  16. --- Start the Tomcat source code. Initialized (loaded class package) analysis of three

    1, start Tomcat is org.apache.catalina.startup.Bootstrap # main () started. Code is as follows: public static ...
  17. Tomcat source code --- load the corresponding resources and Analysis 4 (2)

    1 Based on the above article by talking to the server.xml parsing for the simple analysis of org.apache.catali ...
  18. tomcat source code analysis

    Connector is the core component of the Tomcat is responsible for dealing with a WebServer the core of the conn ...
  19. Tomcat source --- Session of the analysis of the

    First, read the rough in front of tomcat request / response, the next article on tomcat which a detailed analy ...