Today is the 88th day for Liu Xiaoai to learn Java by herself.

Thank you for watching. Thank you.

Without further ado, let’s begin today’s lesson:


Some time ago, I spent 20 days to learn MySQL database, JDBC and some knowledge points of the front end.

This time is certainly far from enough, but after all, Java background is the main, the other is just a little understanding.

  • Database: the place where data is stored. For an enterprise or a project, there is no doubt that data is the most important.
  • Front end: it can deal with the user directly.

The server is tantamount to the database and the front end of the connection.

The server obtains the data from the database, returns it to the front end, and then displays it to the user after rendering.

Do a little summary of knowledge points:


Yesterday we had a comprehensive overview of Tomcat and JavaWeb project creation, and today we will look at the specific operations.

Overview of Servlets

Now there is a requirement that users enter a user name and password through the browser to log in to the web page.

Then the following problems should be solved:

  • Gets data submitted by the user on the web page.
  • Perform the corresponding service logic processing (check whether the database verification user name and password exist)
  • Returns the processing results to the browser.

To solve these problems, the concept of servlets is introduced.

Servlets, which translates as small servers, are a specification made by Java. When it comes to specifications in Java, the first thing that comes to mind is interfaces.


① Implement the servlet interface

Of course there are servlet implementation classes already in Java, but trying to write them yourself will give you a better understanding of the flow.

② Write configuration information in web. XML

The servlet tags:

  • Servlet-name: indicates the label name
  • Servlet-class: fully qualified name of the servlet implementation class (package name + class name)

The servlet – mapping the label:

  • Servlet-name: The label name must be the same as the previous one
  • Url-pattern: indicates a specific mapping path

③ Service handles business logic

Service, which handles the specific business logic in this method, but does not have it yet, and replaces it with an output statement. To see if it’s actually working.

4 Enter the mapping path in the browser

Access the corresponding address, the console will output the corresponding statement.

These are the four steps of servlet writing. You may feel a little confused at first, so you can either memorize them by rote or learn about the process:


① THE URL in the browser

When we click a button on a web page to go to a new page, it corresponds to a different URL, the path to the browser’s address bar.

The server is based on the URL to make different business processes to query the corresponding data.

② Find the corresponding class according to the mapping path

In the browser, the path is /user. Find the corresponding configuration tag in web. XML, and then find the corresponding class name based on the tag name.

③ Find the corresponding class

This class, the fully qualified name in web.xml, has a service method.

The browser enters the corresponding path and finds the service method of the corresponding class based on the configuration information of web. XML.

This is a servlet running flow.

Second, Servlet optimization

Ok, now consider this question:

There are many methods in the Servlet interface, and for us not all of them need to be used, just those we need to use.

So what can we do?

This involves servlet optimization, of course, Java source code has been optimized direct inheritance can be.

But the learning phase had better have an understanding of its optimization process.

1 a servlet optimization


Define a class GenericServlet that implements the Servlet interface and completes the rewrite.

If you need a service method, write it as an abstract method that the implementation class must override.

The subclass overrides the Service method by inheriting GenericServlet, and the other methods of the superclass can be used directly.

2 the servlet optimization of 2

Now, when we learned about forms, we learned that browsers can submit requests in two ways: get and POST.

There is only one service method, so both get and POST commits execute the Service method.

This requires a refinement of the Service method


Define an HttpServlet class that inherits the GenericServlet class.

① Subdivide the service method

Subdivision of service methods by method overloading, where HttpServletRequest is a subclass of ServletRequest and is therefore strong.

② Determine the browser request method

Request. getMethod can get the method of the current request:

  • If it is a GET request, call the doGet() method
  • If it is a POST request, call the doPost() method

③ Define doPost method and doGet method

This subdivides the Service method.

Execution Result:


MyServlet simply inherits the HttpServlet class and overrides the doPost() and doGet() methods, respectively.

Now that the browser sends a request, MyServlet will use its parent class’s Service method to determine how the request is made and then execute the corresponding request method.

Based on the console output, you can tell that the request method here is a GET request.

3 Optimization Summary

In fact, GenericServlet and HttpServlet are already defined in Java.

Its code is similar to the above optimization process, of course, its functions are more complex comprehensive, such as the request method source code doPut() method and doDelete() method.

Look at the diagram of their inheritance system:


Optimization of a:

The GenericServlet class implements the Servlet interface, and there are methods in this class that already implement some functionality, such as the log() method.

In this case, the subclass simply calls the method without having to write how to implement it.

GenericServlet class is equivalent to the function of the Servlet interface expansion and derivation.

Optimization of 2:

The HttpServlet class subdivides browser requests that otherwise execute the Service method.

Servlet life cycle and mapping path

1 Life Cycle

For the Servlet lifecycle, you can create a class that implements the Servlet interface, configure the mapping path of the class, and do a test via browser access:


① The Servlet is initialized

When the corresponding mapping path is accessed by the browser, the init() method executes and the Servlet completes initialization.

(2) the Servlet is executed

The service method is executed every time the browser accesses it.

The difference between this and the init() method is:

  • Init () is only done once on the first access.
  • Service () is executed once with each browser access.

(3) the Servlet is destroyed

When Tomcat is turned off, the destroy method executes and the servlet is destroyed.

It is worth noting:

In the servlet TAB there is a subtag <load-on-startup>1</load-on-startup> with 1 to 5 levels


  • When the tag is present, regardless of the level, the Servlet is initialized as soon as the container (Tomcat in this case) starts.
  • When the tag does not exist, the Servlet is initialized as the browser accesses the corresponding path.
  • The smaller the positive value, the higher the priority of the corresponding Servlet (each Servlet has its own name), and the first the application loads when it starts.
  • If the values are the same, the container selects its own loading order.

2 Mapping Path

One has four ways of matching. You can create these four paths, one for each class, and then test them on the browser.

I’m not going to show you one by one, but just make a summary:


① Perfect match

The browser path must be exactly the same as the mapping path of the Servlet to access the Servlet

② Directory Matching

Format: / directory name /*, which means that any subpath under the current directory can access the Servlet.

③ The suffix name matches

Format: *. Suffix name, that is, any path with this suffix name can access the corresponding Servlet.

If ② and ③ conflict, ② takes precedence.

④ Default Path

Format: /, that is, any path can be used.

** Note: ** has priority ①>②>③>④

4. Servlet annotation development

In our previous code, we had to configure the mapping path of the Servlet in web.xml each time, which caused a problem:

If there are many paths and you need to configure many, many tags, it will appear that the code is bloated, maintenance is not convenient.

Is there an easier way?

In Servlet3.0, there is an annotation development. Let’s try it out:


Instead of New a class in Java, now it’s New a Servlet.

You can use this method when you need to use servlets.

It’s essentially a Java class with an annotation on it.


The value of the annotation is “/AnnoServlet”.

This is equivalent to the mapping path configured in web.xml.

When you type the path in the browser, you can access the class under the corresponding annotation and execute the specific business logic.

And that makes it a lot simpler.

Of course, the Servlet annotation development template can be configured as follows:


Once configured, this custom set of templates will be used every time Servlet annotation development is used.

The code in the template can be modified according to your needs.

The last

Thanks for watching.

If you can, please give it a thumbs up. Thank you.

This article is formatted using MDNICE