Servlet Specification Introduction - How does theWeb framework injected into a servlet?

xiaoxiao2021-03-06  38

introduction

The web framework generally provides a unified request entry through a servlet, maps the specified resource to this servlet, in which the initialization configuration of the frame is performed, access the data in the web page, and perform the logic processing, the result data and performance Layer mismarries are demonstrated to users. The web framework wants to run in a container that complies with the Servlet specification, also complies with the Servlet specification.

Inject a web frame to a servlet, mainly involving the following sections in the Servlet specification:

Ø Deployment descriptor

Ø Mapping request to servlet

Ø Servlet survival cycle

Ø request distribution

Description of Servlet related technical specifications

Deployment descriptor

The deployment descriptor is a web.xml XML file in the / web-infrotive of the web application, which is an integral part of the web application that manages the configuration of the web application. The deployment descriptor passes the element and configuration information of the web application between application developers, application assembly, application deployers.

The following types of configuration and deployment information in the deployment descriptor in the web application are all of the Servlet containers must be supported:

Ø servletContext initialization parameters

Ø session configuration

Ø servlet declaration

Ø servlet mapping

Ø Application Survival Cycle Listener

Ø Filter definition and mapping

Ø MIME type mapping

Ø Welcome file list

Ø Error file list

The security information that appears in the deployment descriptor may not be supported unless this Servlet container is part of the J2EE specification implementation.

All correct web application deployment descriptors (servlet2.3 specification) must contain the following DOCTYPE statement:

Application 2.3 // en "" http://java.sun.com/dtd/web-app_2_3.dtd ">

Hereinafter, how to perform a servlet declaration and mapping in the deployment descriptor, the full content of this DTD can be obtained in the following address:

http://java.sun.com/dtd/web-app_2_3.dtd

The part of the Servlet declaration and mapping and mapping in this DTD is as follows:

The Servlet Element Contains The Declarative Data OF A

Servlet. if a jsp-file is specified and the loading-on-startup element

IS present, THE JSP Should Be Precompiled and Loaded.

Used in: web-app

->

(servlet-class | jsp-file), init-param *, load-on-startup ?, runs ?,

Security-role-ref *)>

The Servlet-Class Element Contains The Fully Qualified Class Name

Of the servlet.

Used in: servlet

->

The servlet-mapping element defines a mapping between a servletand a url pattern

Used in: web-app

->

The servlet-name element contains the canonical name of there

Servlet. Each servlet name is unique within the web application.

Used in: Filter-mapping, servlet, servlet-mapping

->

According to the above DTD, a typical servlet declaration format is as follows:

Catalog

com.mycorp.catalogservlet

Catalog

Spring

A typical servlet mapping is as follows:

Catalog

/ catalog / *

Through the above method, we declare a servlet named Catalog, which implements class as com.mycorp.catalogServlet, and has a Catalog parameter, parameter value is Spring, all requests to / catalog / * are mapped To the servlet named Catalog.

Mapping request to servlet

After receiving a request, the web container is to determine which web application is turned to. The longest context path of the selected application must match the start part of the requested URL. The part of the URL matches is the context path mapped to the servlet.

The next step in the web container must be positioned in accordance with the program below.

The path used to map to the servlet is the path to the URL requested to subtract the context. The following URL path mapping rules are executed in order, and the container selects the first successful match and does not perform the next match:

Ø The container tries exactly match the path to the requesting path and the servlet. If the match is successful, select this servlet.

Ø The container will cycle to match the longest path prefix: put the '/' as a path separator, decrease the completion of the path tree step by step, select the longest matching servlet.

Ø If this last has the final extension (such as .jsp), the servlet container will try to match the servlet that handles this extension.

Ø If the previously do not match the servlet with the previous three rules, the container will try the appropriate resource for resource requests. If there is a "default" servlet definition to this application, then this servlet will be used.

Containers must use a case sensitive matching method.

In the deployment descriptor, use the following syntax definition mapping:

Ø A string that starts with '/' and ends with '/ *' to map the path. Ø A string with '*.' Prefixed to map extensions.

Ø A string containing only '/' is indicating the "default" servlet, in which case the path of the servlet is the requested URI minus the context path, and this path is NULL.

Ø All other characters are only used to accurately match.

If the container has built-in JSP container, * .jsp is mapped to this container and allows the JSP page to be executed when needed. This mapping is called hidden mapping. If the web application is defined in * .jsp, then this mapping has a high priority than an implicit map.

The web container allows explicit declarations to implicit mapping to get priority, for example, *. SHTML's implied mapping can be mapped to contain functions on the server.

Mapping instance:

Path Pattern

servlet

/ FOO / BAR / *

servlet1

/ baz / *

servlet2

/ catalog

servlet3

* .BOP

servlet4

Here is the result of the actual request mapping

incoming path

Servlet Handling Request

/FOO/Bar/index.html

servlet1

/FOO/Bar/index.bop

servlet1

/ baz

servlet2

/BAZ/index.html

servlet2

/ catalog

servlet3

/catalog/index.html

Default "servlet

/catalog/racecar.bop

servlet4

/index.bop

servlet4

Note that both /catalog/index.html and /catalog/racecar.bop, because it is exactly match, so it is not mapped to the process / catalog's servlet.

Servlet survival cycle

Please let a javax.servlet.servlet interface before introducing the SERVET's living cycle. All servlets must be implemented or indirectly implemented, we can usually implement this interface by inheriting javax.servlet.GenericServlet or javax.servlet.http.httpservlet.

The following five methods are defined in this interface:

Public void init (servletconfig); public servletconfig getServletConfig (); public void service (servletRequest Req, servletResponse res); public string getServletInfo (); public void destroy ();

INIT () method

The init method is executed when the container is loaded, and the servlet container only calls only the init method after instantiation, and the init method must be completed before the servlet is received any request.

This method is usually used to manage and initialize some resources, such as reading the configuration data from the configuration file, reading initialization parameters, initialization buffer, etc. one-time operation.

GetServletConfig () method

GetServletConfig method returns a servletconfig object, which is used to return this servlet's initialization information and startup parameters. The returned is passed to the init method servletconfig.

Service () method

The Service method is the entry point of the application logic. It is the core of the servlet method. The Web container calls this method to respond to the request, only the servlet is successfully initialized by the init () method, the service method will be called.

GetServletInfo () method

This method returns a string object to provide information about servlet, such as author, version, etc.

DESTROY () method

The DESTROY method is executed when the container is removed, and only once. This method will execute after all the service () method of all threads or timeout, the container will not call this servlet, that is, the container will no longer send the request to this servlet. This method gives the servlet to release the opportunity to occupy the resource, usually used to perform some cleaning tasks.

This interface defines the method of initializing a servlet, service request, and removing servlet from the container. They perform in the order below:

1. After the servlet is instantiated, initialize in the init method

2. Call the service method any request from the client

3. Servlet is removed, call the destroy method to destroy

servlet

The living cycle is as follows:

Request distribution

Request distribution allows a servlet to assign a request to another resource, and the RequestDispatcher interface provides a mechanism for achieving his mechanism. You can get an object that implements the RequestDispatcher interface from ServletContext by the following two ways:

• GetRequestDispatcher

• GetNamedDispatcher

GetRequestDispatcher method accepts a URL path pointing to the target resource

RequestDispatcher rd = getServletContext (). GetRequestDispatcher ("/ catalog");

GetNamedDispatcher method accepts a servlet name parameter, which is the name specified by the element in the deployment descriptor.

RequestDispatcher rd = getServletContext (). Getnameddispatcher ("catalog");

There are two ways of the requestDispatcher interface, allowing you to assign the request response to another resource after the initial process is completed.

FORWARD () method:

Public Void Forward (ServletRequest Request, ServletReponse Reponse) THROWS SWERLETEXCEPTION, IOEXCEPTION

The Forward method allows you to forward the request to other servlets or JSP or HTML and other resources, which will be responsible for responding by this resource. Such as:

RequestDispatcher rd = getServletContext (). GetRequestDispatcher ("/ catalog"); RD. Forward (Request, Response);

Include () method:

Public Void Include (ServletRequest Request, ServletReponse Reponse) THROWS SWERLETEXCEPTION, IOEXCEPTION

Include method Let your servlet response contain another resource generation content

RequestDispatcher rd = getServletContext (). GetRequestDispatcher ("/ catalog"); rd. Include (Request, Response);

Combined with the specific analysis of Webwork

WebWork is a J2EE web framework for developing the OpenSymphony organization to implement the MVC mode. After introducing the relevant content of the Servlet specification, let's see how the webwork is injecting into a servlet, assuming we have a web application for the context environment "/ webworkDDemo". Deployment descriptor

In the deployment descriptor, we need to configure the following:

Webwork

com.opensymphony.Webwork.dispatcher.servletdispatcher

......

Webwork

*. action

We declare a servlet and * .Action to this servlet, which is the WEBWORK, which is a very important controller role in the webwork.

Mapping request to servlet

There is a clip in xwork.xml in Xwork.xml:

/ demo.jsp

This way we make a request to the server by http: // localhost: 8080 / webdeemo / demo.action, the web container first determines which web application, the container matches the request URL and the context environment and know will go to / WebWorkDdemo This web application.

Next, the container will find the servlet of this request in the deployment descriptor of / webddemo, find the name webwork this servlet according to the suffix * .An, which is mapped to the Controller component in Webwork based on the deployment descriptor. Com.opensymphony.WebWork.dispatcher.Servletdispatcher is handled. This servlet for the controller assembly is handled in his service () method in parsing the corresponding action in accordance with the requested path.

Through the above processing, the WEB request to the controller servletdispatcher in Webwork. Not only is the webwork, implementing the MVC web framework requires similar processing to transfer web requests to their own Controller. For further processing.

Servlet survival cycle

ServletDispatcher This servlet's memory usage can be as follows:

1) When the server is started, the container first instantiate servletdispatcher.

2) After instantiation is completed, the init () method will be called, and the following is performed in the init method:

Ø Initialize the Velocity engine

Ø Check if the configuration file reload function is supported. If support, each request request will reload the xwork.xml configuration file, which is very convenient to development. Ø Set information uploaded by some files, such as uploading a temporary directory, uploading the maximum byte, etc.

3) The service () method is called each request, and the following method is performed in the service method.

Ø Get the namespace of Action via request request

Ø According to the prevlet request, resolve the name of the Action to call the request (ActionName)

Ø Create an action context, traversed the data in httpservletRequest, HttpSession, servletContext, and copy it to the webwork MAP implementation, and all data operations are performed in this MAP structure, thereby using internal structure and servlet API. Phase separation.

Ø Use the information as the parameters, call ActionProxyFactory to create a corresponding ActionProxy instance. ActionProxyFactory will create an ActionProxy instance according to the settings in the XWork.xml, and the ActionProxy contains configuration information (including the Action name, corresponding to implementation class, etc.).

Ø Execute the execute () method of proxy

4) Perform DESTROY () when the container is removed, and does not override the Destroy method in servletdispatcher. When removing the servlet, it will not do anything.

Request distribution

Webwork provides a variety of ways to show, such as the configuration we are above xwork.xml:

/ demo.jsp

According to the above configuration When the return value of the demoaction is "success", "Dispatcher", when the result is "Dispatcher", the resulting result will be processed by javax.servlet.RequestDispatcher's forward () or include () method. Delivering layer fusion

We can look at the Dispatcher Type Result Type of the webwork, the code snippets in the COM.Opensymphony .WebWork.dispatcher.ServletdispatcherResult:

HttpServletRequest request = ServletActionContext.getRequest (); HttpServletResponse response = ServletActionContext.getResponse (); RequestDispatcher dispatcher = request.getRequestDispatcher (finalLocation); if (dispatcher == null) {response.sendError (404, "result '" finalLocation " 'not found "); return;} = f (!") get (("javax.servlet.include.servlet_path") == NULL) {Request.SetaTRibute ("Webwork.View_uri", FinalLocation ); request.setAttribute ( "webwork.request_uri", request.getRequestURI ()); dispatcher.forward (request, response);} else {dispatcher.include (request, response);} ServletDispatcherResult class obtained from HttpServletRequest and ServletActionContex HttpServletResponse, then call request.getRequestDispatcher (finalLocation) method to get a RequestDispatcher instance, if the return is null, then the output error 404 page not found, otherwise it will call dispatcher.forward (request, response) or dispatcher.include (request, response ) Request distribution, exhibiting processing results and performance layers to the user.

Conclude

Through the above introduction, we have a simple understanding of the web framework into the servlet. If you want more in-depth research, you can read the servlet specification and some of the source code of some mature frames.

Written By absolute zero

Email: hongjunshi@gmail.com

转载请注明原文地址:https://www.9cbs.com/read-69330.html

New Post(0)