Servlet Summary (i)

Source: Internet
Author: User
First, the preface
The servlet is the solution that Java's programming language provides for how to generate dynamic Web pages. As I have analyzed in an earlier article, the so-called Web page is actually a bunch of HTML tags, and the browser is responsible for parsing the tags and showing what we see. The HTML markup browser itself is not, it wants to go with the server, because only the server has.
So how does the HTML on the server come from? In two ways, one is static, that is, we save the HTML tags in a text file in advance, and then the. html is the suffix name. Each time you access the file, you get the same HTML tag, unless you modify the file, which is called "Static". Another is the so-called dynamic, HTML tags are not manual, and by the program automatically generated by the input conditions, the browser each access to the program may obtain different HTML tags, which is called "dynamic."
As for the HTML tag-generated program, the browser is not really concerned, you just give me a complete HTML tag. There are a lot of languages to do this now, in addition to Java, PHP, Python, Ruby, and even C. Because really, is not to generate a pair of HTML format strings, too simple.
Well, it's simple, so I chose Java. In fact, Java is very powerful, can do a lot of things, a servlet technology is just one of them. Servlet technology by the container plus the servlet interface two parts, we usually develop in fact just an interface, but the optical interface is unable to complete the production of HTML tags Albert, but also need to support the container. I think that when the servlet technology was just born, it should not be so subdivided. Just as the requirements change, the generation of HTML tags is becoming more and more complex, requires division of labor and specialization, so the original whole into a container and interface two parts, the container provides the underlying support, while the interface is focused on the specific business. It can be simply understood that the container is the implementation of the interface, and the interface is the API that the servlet exposes to us, and we just need to focus on how to use these APIs to implement our own business logic. But since the realization of the interface, it is not only a realization, we are familiar with Tomcat is only one of them, the others are jetty, GlassFish, JBoss and so on.
I write this series of articles, the first step is to analyze these interfaces, and then analyze one of the implementations, that is, Tomcat.

Second, Servlet API
The servlet that we normally use is just an API that has evidence, first of all, the jar name we introduced when using MAVEN as a project, as shown in the following figure:

Then look at the content schema for the jar package:

A lot of things, look at the servlet this most important "class":

Wow, it's a interface. Most of the classes in this package are actually interfaces.
The servlet's API is divided into three major chunks: servlet, filter, and listener, which can be verified from the class name in the package. Then, mainly to have a child packet called HTTP, this package of things specifically used to deal with the HTTP protocol related things. This means that when the servlet was first designed, it was actually more scalable, not just for HTTP, but for other types of protocols. However, because of the dominance of the HTTP protocol in the Web, the servlet has added a child package specifically for HTTP.

Third, the Servlet
First look at the method in this interface:
Public interface Servlet {public
    void init (servletconfig config) throws servletexception;
    Public ServletConfig getservletconfig ();
    public void Service (ServletRequest req, servletresponse Res) throws Servletexception, IOException;
    Public String getservletinfo ();
    public void Destroy ();
}
Implementing this interface is what business development is all about, and they want to implement all the business logic in these approaches. Observations can be found that there is no main method in the interface, so how to implement the implementation class. This is the responsibility of the vessel. The container is responsible for managing the implementation classes of the Servlet interface, invoking different methods at different stages. The main method is in the container.
A servlet book or article will refer to the lifecycle, which is actually controlled by the container, which invokes the Init and destroy methods only once, but calls the service method repeatedly every time the request arrives. So when implementing this interface, initialization works in Init, cleanup work in Destroy, and the main business logic is in service.
The other two methods are auxiliary, where getservletinfo is rarely used, its task is to return descriptive information about the implementation class, and another method Getservletconfig more important, and its task is to obtain the initialization parameters of the Servlet implementation class from the configuration file. This means that the initialization parameters of the servlet are not placed inside the implementation class itself, but rather in the configuration file. There's nothing wrong with that. Am I just going to put a few private variables in the implementation class? Of course, but as you can see from the existence of this method, the getservletconfig of the servlet do not recommend this, especially if this parameter is closely related to the business and often needs to be changed. In fact, the container only creates an object for each servlet's implementation class, and only this object is used to meet all requests to access it. When more than one request, in order to efficiency must open multithreading. In other words, there will be multiple threads accessing the service method of this object, and if the private variable is modified in the service method, it will inevitably result in inconsistent data, and if the private variable is set to sync, it will result in a decrease in efficiency. So the initialization parameters are placed in the configuration file, but the servlet interface does not modify their method, which means that the initialization parameters are read-only when the program is running, and to change the parameter values, the configuration file can only be modified before the program is run.
However, to do this can also be done by setting the private variable to final. But to change the parameter value, it is convenient to modify the class code or modify the configuration file.

Then take a look at the first method Init, which needs to pass in a servletconfig parameter when invoked by the container, indicating that the container has generated a ServletConfig object based on the configuration file. So what to do in the Init method. Corresponding to the second method Getservletconfig, it returns a ServletConfig object from where it comes from. This object must be the ServletConfig object that was passed in when the container called init, so the code should be like this:

public class Myservlet implements Servlet {
    private servletconfig servletconfig;


    Public init (ServletConfig servletconfig) throw servletexception {
        this.servletconfig = servletconfig;
    }


    Public ServletConfig Getservletconfig () {return
        this.servletconfig;
    }
    ...
}

In other words, the implementation class still has to have a private servletconfig variable, and it is necessary. Thankfully, this variable has nothing to do with the business, and usually you just use it to get information. The first task of Init must initialize this servletconfig variable.

Then analyze the service method, he has two parameters ServletRequest and Servletresponse, these two parameters are obviously also the container passed in. When the request arrives, the container encapsulates the request into a ServletRequest object, generating a Servletresponse object, which is passed to the servlet. The latter obtains the necessary information from the ServletRequest object and then writes the processing result to the Servletresponse object. It should be noted that both ServletRequest and servletresponse are interfaces, and their implementation is done by the container.

Four, ServletConfig interface
This interface is also responsible for the implementation of the JONGTI, you can see that all the interface involved in the underlying support is responsible for the implementation of the container, and the business is the implementation of their own, I think this design is very good. First look at the architecture of the interface:

Public interface ServletConfig {public
    String getservletname ();
    Public ServletContext getservletcontext ();
    public string Getinitparameter (string name);
    Public enumeration<string> getinitparameternames ();
}

There are only four methods, the most important of which is, of course, the last two, to get the parameters in the configuration file. But before you analyze them, you need to know exactly what the configuration file is and where it is. This starts with the Web application directory structure defined by the servlet specification. A Dynamic Web application contains servlet-compiled class files, HTML static files, JSP files, JS scripts, various configuration files and image files, and other multimedia resource files. These files obviously cannot be mixed into a directory. Whether using Tomcat or jetty as a container, you must first have your own engineering directory to store the above documents. For example, the project directory named MyWeb, then the servlet specification stipulates myweb must have a web-inf directory. The Web-inf directory has two subdirectories classes and LIB, which store the compiled class file, which stores the jar package used. Web-inf also need to have one of the most important configuration files, this is our familiar web.xml:

<web-app>
  <servlet>
  	<servlet-name>CometServlet</servlet-name>
  	< Servlet-class>comet. cometservlet</servlet-class>
  </servlet>


  <servlet-mapping>
  	<servlet-name> cometservlet</servlet-name>
  	<url-pattern>/test/comet</url-pattern>
  </ Servlet-mapping>
</web-app>
The top-most label is Web-app, and there are a lot of sub tags underneath it, but now we're going to focus on <servlet> and <servlet-mapping>

We see that there are two elements:<servlet-name> and <servlet-class> in the <servlet> tag, which is the fully qualified class name of the servlet implementation class, and the container automatically from the web-inf/ Classes directory to find, and the former is the name we give it-can be arbitrarily named. The Getservletname method is usually the name returned. The name is for <servlet-mapping> service, the main role of this tag maps a URL to a servlet, and when the browser accesses the URL, the container invokes the Servlet's service method. Returns the HTML tag it produces to the browser.
Here it is necessary to mention the URL: the URL in the configuration file is clearly not a complete URL, it is prefixed with a prefix including three parts, IP, port number, Web application name. Where the IP and port numbers are separated by a colon, but the Web application name can be empty. When you access IP directly in the browser: port number, such as localhost:8080, the path that the browser actually accesses is localhost:8080/, which is the default plus a slash. This slash represents the root directory, and as to which Web application the root directory refers to, different containers have different scenarios, such as Tomcat accessing the root directory. To distinguish the default values of the root directory, it is best to use a meaningful name for your Web application. For Tomcat, the name of the application is configured in the Server.xml file, the details first refer to here, and when I interpret the Tomcat source code will be carefully analyzed.
After the application name generally no longer has a slash, so the value of the <url-pattern> tag often begins with a slash, and the part following the slash can be a regular expression, such as/* representing any path. That is, all requests to access this Web application will be handled by the corresponding servlet. Of course, the value can be written very specific, then the corresponding servlet is responsible for only this URL request. But here's one thing to be very careful about: specific URLs have higher precedence than the generic URLs. For example Servlet1 corresponding URL is/*, and Servlet2 corresponds to the URL is/test, then the browser access to/test, the container will first call Servlet2.

Well, I haven't talked about ServletConfig for half a day. The servlet initialization parameters are defined within the <servlet> label as follows:

<servlet>
  	<servlet-name>CometServlet</servlet-name>
  	<servlet-class>comet. cometservlet</servlet-class>
	<init-param>
          <param-name>color</param-name>
          <param-value>red</param-value>
      </init-param>
</servlet>
<param-name> Label definition parameter name,<param-value> given the parameter values, they are two to be surrounded by <init-param>. Multiple <init-param> tags are required when multiple initialization parameters are defined. The parameters defined in the configuration file are removed by a string type, with a unique type. The Getinitparameternames method returns enumeration, which contains all of the <init-param>.
When does the container read these initialization parameters in the configuration file? The first thing to understand is that when the container starts, it does not load all the servlet into memory immediately, but waits until the browser accesses the URL to load the servlet, which is the object of the new implementation class. Read initialization parameters should be before the object is new and the Init method is invoked.
ServletConfig Another method is Getservletcontext, which returns a ServletContext object, which we'll analyze later.

Let's write so much in this article.

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.