How Servlet works

Source: Internet
Author: User

How Servlet works
I. Starting from servlet containers
Servlet containers have many implementations, such as Jetty and Tomcat. Tomcat is used as an example here. In the Tomcat container level, the Context container directly manages the Wrapper class of the Servlet in the container. Therefore, how the Context container runs will directly affect the Servlet's working mode. The Tomcat container model is as follows:

We can see that Tomcat containers are divided into four levels. The container that actually manages Servlet is the Context container, and one Context corresponds to one Web project, in the Tomcat configuration file, you can easily defend against this point:
<Context path = "/projectOne" docBase = "D: \ projects \ projectOne" reloadable = "true"/>
The following describes in detail the process of parsing the Context container by Tomcat, including how to build a Servlet.
1. servlet container Startup Process
Tomcat 7 supports embedded functions, that is, adding a startup class org. apache. catalina. startup. Tomcat. You can easily start Tomcat by creating an instance object and calling the start method. We can also use this object to add and modify Tomcat configuration parameters, such as dynamically adding Context and servlet.
Tomcat's startup logic is designed based on the observer mode. All containers inherit the Lifecycle interface, which manages the entire Lifecycle of containers, all modifications to the container and changes to the status will notify the registered observer (Listener ). The following figure shows the sequence of Tomcat startup:

2. web application Initialization
The Web application Initialization is implemented in the configureStart method of ContextConfig. The application Initialization is mainly to parse the web. xml file, which describes the key information of a Web application and is also the portal of a Web application. The configuration items in the web. xml file are parsed into corresponding attributes and saved in the WebXml object. Attributes in the WebXml object will be set to the Context container, including creating Servlet objects, filters, and listener. Therefore, the Context container is the Servlet container that truly runs the Servlet. A Web application corresponds to a Context container. The container configuration attribute is specified by the web. xml of the application.

Ii. Create a servlet instance
1. Create a servlet object
If the Servlet load-on-startup configuration item is greater than 0, it will be instantiated when the Context container is started. By default, two servlets will be started, which are org. apache. catalina. servlets. defaultServlet and org. apache. jasper. servlet. jspServlet. Their load-on-startup values are 1 and 3, respectively.
The method for creating a Servlet instance starts with Wrapper. loadServlet. The loadServlet method must acquire the servletClass and hand it over to InstanceManager to create an object for the opportunity servletClass. class. If jsp-file is configured for this Servlet, this servletClass is org. apache. jasper. servlet. JspServlet defined in conf/web. xml.
2. initialize servlet
Initialize the Servlet in the initServlet method of StandardWrapper. This method calls the Servlet init () method and transmits the StandardWrapperFacade of the StandardWrapper object to the Servlet as the ServletConfig. If the Servlet is associated with a JSP file, JspServlet is initialized first. Next, a simple request is simulated to call the JSP file to compile the JSP file as a class, and initialize this class. In this way, the Servlet object initialization is complete.

Iii. servlet Architecture
The Association diagram of Servlet top-level classes is as follows:

It can be seen that the three classes associated with Servlet are ServletConfig, ServletRequest, and ServletResponse.
The Request and Response classes corresponding to one Request are converted as follows:


4. How does servlet work?
A request sent from a browser to the server usually contains the following information: http: // hostname: port/contextpath/servletpath, hostname and port are used to establish a TCP connection with the server, the following URL is used to select the sub-container service user's request on the server. In Tomcat, URLs and Servlet containers use the org. apache. tomcat. util. http. mapper to complete the ing. Mapper sets the host and context container to the mappingData attribute of the Request based on the requested hostname and contextpath.
Servlet can help us complete all the work, but today's Web applications seldom directly implement all the pages of interaction with Servlet, but adopt a more efficient MVC framework. The basic principle of these MVC frameworks is to map all requests to a Servlet and then implement the service method, which is the entry of the MVC framework.
When the Servlet is removed from the Servlet container, it also indicates that the Servlet's lifecycle is over. At this time, the Servlet's destroy method will be called for some scanning.

5. listener in servlet
The Listener is widely used on the Tomcat server. It is designed based on the observer mode. The Listener design provides a quick way to develop Servlet applications, you can easily control programs and data from another vertical dimension. Currently, Servlet provides the following types:

They basically cover all the events you are interested in throughout the Servlet lifecycle. These Listener implementation classes can be configured on the web. you can also add listener to the xml <Listener> tag in the application, but the ServletContextListener cannot be added after the container is started, because the event it listens to will no longer appear.

6. How filters work
Filter is another common configuration item in web. xml. You can use filter by combining <filter> and <Filter-mapping>. In fact, the Filter can do the same work as Servlet, or even be more flexible, because it not only provides the request and response objects, but also provides a FilterChain object, this object allows us to control the transfer of requests more flexibly. The following is the structure of the Filter-related class:

The significance of Filter is that you want to go to Beijing and it is your destination, but it provides a mechanism for you to intercept some work while you are on the way, for example, you can store some of your luggage bags somewhere. When you return, you can retrieve them from this place, which allows you to increase or decrease some items on the way.

7. url-pattern in servlet
In web. xml, <servlet-mapping> and <filter-mapping> both have <url-pattern> configuration items, which match whether a request will execute the Servlet or Filter.
A request is finally allocated to a Servlet through org. apache. tomcat. util. http. the Mapper class is complete. This class matches the configured <URL-pattern> in each Servlet according to the requested url, so it matches when a request is created.
The Filter url-pattern match is performed when the ApplicationFilterChain object is created. It matches the url-pattern of all the defined filters with the current URL, if the match succeeds, the Filter is saved to the filters array of ApplicationFilterChain and called in the FilterChain.
In the web. during xml loading, the system first checks whether the <url-pattern> configuration complies with the rules. This check is performed in the validateURLPattern method of StandardContext. If the check fails, the Context container fails to start, and the java. lang. illegalArgumentException: Invalid <url-pattern>//*. htm in Servlet mapping error.
There are three matching rules for <url-pattern>:
(1) exact match: for example,/foo.htmonly matches the foo.htm URL.
(2) Path Matching: for example,/foo/* will match the URL prefixed with foo.
(3) Suffix matching: for example, * .htmwill match all URLs with a suffix of .htm.


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.