Introduction to the Servlet specification

Source: Internet
Author: User

Introduction

A WEB framework typically provides a uniform request portal through a servlet that maps the specified resource to the servlet, initializes the framework in the servlet, accesses the data in the Web page, and logically processes the resulting data into the presentation layer and presents it to the user. The WEB framework wants to run in a container that conforms to the servlet specification and also conforms to the servlet specification.

Injecting a WEB framework into a servlet mainly involves the following parts of the servlet specification:

Ø Deployment Descriptor

Ø Map Request to Servlet

Øservlet life cycle

Ø Request for distribution

ServletIntroduction to relevant technical specificationsDeployment Descriptor

The deployment descriptor is an XML file that is located in the Web application's/web-inf directory, the Web application, and is an integral part of the website that manages the configuration of the Web application. The deployment descriptor passes the elements and configuration information of the WEB application between the application developer, the application assembler, and the application Deployer.

The following types of configuration and deployment information in the deployment description descriptor of the WEB application are supported by all servlet containers:

Øservletcontext Initialization Parameters

Øsession Configuration

Øservlet statement

Øservlet Mapping

Ø Application life cycle listener

Definition and mapping of Øfilter

Ømime Types of mappings

Ø Welcome File List

Ø Error File List

Security information that appears in the deployment descriptor may not be supported unless the Servlet container is part of the Java EE specification implementation.

All the correct WEB application deployment descriptors (Servlet2.3 specifications) must contain the following DOCTYPE declaration:

<! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD web

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

The following is a description of how Servlet declarations and mappings are made in the deployment descriptor, and the entire contents of this DTD can be obtained at the following address:

HTTP://JAVA.SUN.COM/DTD/WEB-APP_2_3.DTD

The sections in this DTD for Servlet declarations and mappings and mappings are as follows:

<!--

The servlet element contains the declarative data of a

Servlet. If a jsp-file is specified and the Load-on-startup element

Is present, then the JSP should be precompiled and loaded.

Used In:web-app

-

<! ELEMENT servlet (icon, Servlet-name, display-name?, description?,

(Servlet-class|jsp-file), init-param*, Load-on-startup?, runas?,

security-role-ref*) >

<!--

The Servlet-class element contains the fully qualified class name

of the servlet.

Used In:servlet

-

<! ELEMENT servlet-class (#PCDATA) >

<!--

The servlet-mapping element defines a mapping between a servlet

and a URL pattern

Used In:web-app

-

<! ELEMENT servlet-mapping (Servlet-name, Url-pattern) >

<!--

The Servlet-name element contains the canonical name of the

Servlet. Each servlet name is a unique within the Web application.

Used in:filter-mapping, servlet, servlet-mapping

-

<! ELEMENT servlet-name (#PCDATA) >

According to the DTD above, a typical Servlet declaration is in the following format:

<servlet>

<servlet-name>catalog</servlet-name>

<servlet-class>com.mycorp.CatalogServlet</servlet-class>

<init-param>

<param-name>catalog</param-name>

<param-value>Spring</param-value>

</init-param>

</servlet>

A typical servlet mapping is as follows:

<servlet-mapping>

<servlet-name>catalog</servlet-name>

<url-pattern>/catalog/*</url-pattern>

</servlet-mapping>

Using the above method, we declare a servlet named catalog, whose implementation class is Com.mycorp.CatalogServlet, with a catalog parameter with a value of spring, all to/catalog/* Requests are mapped to a servlet named catalog.

mapping requests to Servlets

After a request is received, the Web container determines which Web application to go to. The longest context path of the selected application must match the starting part of the requested URL. The part of the URL match is the context path that is mapped to the servlet.

The WEB container next must locate the servlet that handles the request in the following program.

The path used to map to the servlet is the URL of the request object minus the context path. The following URL path mapping rules execute sequentially, and the container chooses the first successful match and does not make the next match:

The container tries to exact match the path of the request to the path of the servlet and selects the servlet if the match succeeds.

Ø the container will loop to try to match the longest path prefix: Take '/' as the path delimiter, follow the path tree progressively descending, select the longest matching servlet.

Ø if the URL path has the last extension (for example,. jsp), the servlet container tries to match the servlet that handles the extension.

Ø If there is no servlet in front of the previous three rules, the container will try to provide the appropriate resources for the resource request, and if a "default" servlet is defined for the application, the servlet is used.

The container must use a case-sensitive matching method.

In the deployment descriptor, define the mappings with the following syntax:

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

Ø one with ' *. ' The prefix string is used to map the extension.

Ø one string containing only '/' indicates the "default" servlet for this application, in which case the servlet path is the requested URI minus the context path, and the path is null.

Ø all other characters are used only for exact matching.

If the container has a JSP container built into it, then *.jsp is mapped to the container and allows the JSP page to be executed when needed. This mapping is called implicit mapping. If a *.jsp mapping is defined in the Web application, then this mapping has a higher precedence than the implied mappings.

The WEB container allows explicit declaration of implicit mappings to get precedence, for example, the implicit mapping of *.shtml can be mapped to include functionality on the server.

Map instances:

Path pattern

Servlet

/foo/bar/*

Servlet1

/baz/*

Servlet2

/catalog

Servlet3

*.bop

Servlet4

The following 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

The "Default" servlet

/catalog/racecar.bop

Servlet4

/index.bop

Servlet4

Note that both/catalog/index.html and/catalog/racecar.bop, because they are exact matches, are not mapped to servlets that handle/catalog.

Servlet life cycle

Before you introduce the life cycle of a Servlet, you need to introduce the Javax.servlet.Servlet interface. All servlets must implement or indirectly implement this excuse, and we can usually inherit javax.servlet.GenericServlet or Javax.servlet.http.HttpServlet. Class to implement this interface.

The following 5 methods are defined in this interface:

public void init (servletconfig config);

Public ServletConfig getservletconfig ();

public void Service (ServletRequest req, servletresponse res);

Public String getservletinfo ();

public void Destroy ();

Init () method

The Init method executes when the container is loaded into the servlet, and the servlet container invokes only one Init method after instantiation, and the Init method must be completed before the servlet receives any requests.

This method is often used to manage and initialize some resources, such as reading configuration data from a configuration file, reading initialization parameters, initializing a one-time buffer delay, and so on.

Getservletconfig () method

The Getservletconfig method returns an ServletConfig object that is used to return initialization information and startup parameters for this Servlet. The return is passed to the Init method ServletConfig.

Service () method

The service method is the entry point of the application logic, the core of the Servlet method, which is called by the WEB container to respond to incoming requests, and the service method is called only after the servlet is successfully initialized by the Init () method.

Getservletinfo () method

This method returns a String object that provides information about the servlet, such as author, version, and so on.

Destroy () method

The Destroy method executes when the container removes the Servlet, and it executes only once.       This method executes after the service () method of all threads executes or times out, and after this method is called, the container no longer calls the servlet's method, which means that the container will not send the request to the servlet. This method frees the servlet of the resources it consumes, and is typically used to perform some cleanup tasks.

This interface defines a method of initializing a servlet, a service request, and removing a servlet from a device. They are executed in the following order:

1. When the servlet is instantiated, it is initialized with the Init method

2. Any request from the client invokes the service method

3. The servlet is removed from the service and called by the Destroy method to destroy

The life cycle of a servlet is as follows:

Request Distribution

Request distribution allows one servlet to assign a request to another resource, and the RequestDispatcher interface provides a mechanism to implement it. An object that implements the RequestDispatcher interface can be obtained from ServletContext in the following two ways:

Getrequestdispatcher

Getnameddispatcher

The Getrequestdispatcher method accepts a URL path that points to the target resource

RequestDispatcher rd = Getservletcontext (). Getrequestdispatcher ("/catalog");

The Getnameddispatcher method accepts a servlet name parameter, which is the name specified in the deployment descriptor <servlet-name> element.

RequestDispatcher rd = Getservletcontext (). Getnameddispatcher ("Catalog");

The RequestDispatcher interface has two methods that allow you to assign a request response to another resource after the calling servlet completes the initial processing.

Forward () Method:

public void forward (ServletRequest request, Servletreponse reponse) throws Swerletexception,ioexception

The forward method allows you to forward requests to other resources such as a servlet or JSP or HTML, which is then responsible for the response. Such as:

RequestDispatcher rd = Getservletcontext (). Getrequestdispatcher ("/catalog");

Rd. Forward (Request,response);

Include () Method:

public void include (ServletRequest request, Servletreponse reponse) throws Swerletexception,ioexception

The Include method lets your servlet response contain another resource generation content

RequestDispatcher rd = Getservletcontext (). Getrequestdispatcher ("/catalog");

Rd. include (request,response);

CombineWebWorkThe specific analysis

WebWork is a Java EE web framework developed by the Opensymphony organization to implement the MVC pattern. After introducing the content of the servlet specification, let's look at how webwork is injected into a servlet, assuming we have a Web application with a context of "/webworkddemo".

Deployment Descriptor

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

<servlet>

<servlet-name>webwork</servlet-name>

<servlet-class>com.opensymphony.webwork.dispatcher.ServletDispatcher</servlet-class>

</servlet>

......

<servlet-mapping>

<servlet-name>webwork</servlet-name>

<url-pattern>*.action</url-pattern>

</servlet-mapping>

We declare a servlet and *.action to this servlet, called WebWork, which is the controller in WebWork, which acts as a very important director in the MVC framework.

mapping requests to Servlets

The following fragment is in the Xwork configuration file Xwork.xml:

<action name= "Demo" class= "Webworkapp. Demoaction ">

<result name= "Success" type= "Dispatcher" >

<param name= "Location" >/demo.jsp</param>

</result>

</action>

So that when we make a request to the server by the http://localhost:8080/WebWorkDemo/demo.action URL, the Web container first determines which Web application to go to, After the container matches the request URL with the context, it knows that it will go to the/webworkddemo Web App.

The container then finds the servlet that handles the request in the deployment descriptor of the/webworkddemo application, finds the servlet with the name webwork according to the suffix *.action, so that, depending on the deployment descriptor, This request is mapped to the controller component Com.opensymphony.webwork.dispatcher.ServletDispatcher in WebWork to handle. The servlet acting as the controller component resolves the corresponding action on the requested path in his service () method.

Through the above processing, the implementation of the Web request to the WebWork controller servletdispatcher. More than just webwork, the web framework that implements MVC requires similar processing to transfer Web requests to its own controller. For further processing.

servlet life cycle

Servletdispatcher this servlet's storage cycle can be as follows:

1) When the server starts, the container first instantiates the Servletdispatcher

2) When the instantiation is complete, the init () method is called and the following actions are performed in the Init method:

    • Initializing the Velocity engine
    • Check whether the configuration file reload feature is supported. If supported, the Xwork.xml configuration file will be reloaded for each requests request, which is very handy for development.
    • Set up some file upload information, such as: Upload temporary directory, upload the maximum bytes and so on.

3) Each request invokes the service () method, and the following methods are executed in the service method

    • Get the action namespace by requesting request
    • Resolves the name of the action to invoke the request, based on the path requested by the servlet (ActionName)
    • Create the action context (Extracontext), traverse the data in HttpServletRequest, HttpSession, ServletContext, and copy it to the WebWork map implementation, All data operations are performed in this map structure, separating the internal structure from the Servlet API.
    • With the above information as a parameter, call Actionproxyfactory to create the corresponding Actionproxy instance. Actionproxyfactory will create the Actionproxy instance based on the settings in the Xwork configuration file (Xwork.xml), and the Actionproxy contains the action's configuration information (including the action name, the corresponding implementation class, and so on).
    • Execute () method for executing proxy

4) When the container removes the servlet, it executes destroy (), and in Servletdispatcher this servlet does not override the Destroy method, and when the servlet is removed, nothing is done.

Request Distribution

WebWork offers a variety of live flexible views, such as the one we've configured in Xwork.xml above:

<action name= "Demo" class= "Webworkapp. Demoaction ">

<result name= "Success" type= "Dispatcher" >

<param name= "Location" >/demo.jsp</param>

</result>

</action>

According to the above configuration, when the return value of Demoaction is "success", the processing type is "dispatcher" when the type of result is "dispatcher". The Javax.servlet.RequestDispatcher's forward () or include () method combines the processing results with the presentation layer to show the user

We can look at the code snippet in the implementation class Com.opensymphony. Webwork.dispatcher.ServletDispatcherResult that WebWork provides dispatcher type result type:

  HttpServletRequest request = Servletactioncontext.getrequest ();

  HttpServletResponse response = Servletactioncontext.getresponse ();

  RequestDispatcher Dispatcher = Request.getrequestdispatcher (finallocation);

 

  if (dispatcher = = null) {

    response.senderror (404, "result '" + finallocation + "' Not f Ound ");  

    return;

 }

 

  if (!response.iscommitted () && (Request.getattribute ("javax.servlet.include.servlet_path") = = null ) {

    request.setattribute ("Webwork.view_uri", finallocation);

    request.setattribute ("Webwork.request_uri", Request.getrequesturi ());

   

    Dispatcher.forward (request, response);

 } else {

    dispatcher.include (request, response);

 }

HttpServletRequest and HttpServletResponse are obtained from the Servletactioncontex of the Servletdispatcherresult class, The Request.getrequestdispatcher (finallocation) method is then called to get a RequestDispatcher instance, and if NULL is returned, the output 404 page did not find an error, Otherwise, Dispatcher.forward (request, response), or dispatcher.include (request, response) will be called for distribution, and the processing result and presentation layer are fused and presented to the user.

Conclusion

Through the above introduction, we have a simple understanding of how the Web framework is injected into the servlet, and if you want to do more in-depth research, you can read the servlet specification as well as some mature framework of the source code.

Introduction to the Servlet specification

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.