Github stars 81k! Ali's unique Servlet actual combat notes were exposed for the first time and won millions of collections

Github stars 81k! Ali's unique Servlet actual combat notes were exposed for the first time and won millions of collections

Hello, today I will share the introduction of Servlet to all children's shoes, please take out a small book and write it down!

1. What is Servlet?

    If a web project wants to run on a web server (TomCat, JBoss, etc.), it must meet a set of rules. Servlet is the rule

    This set of rules is formulated by SUN company (the core of Servlet specification is Servlet interface), which belongs to JavaEE specification, and we JAVA programmers write the implementation class of Servlet

2. The role and function of web projects

    web server:

        Manage web projects according to certain rules

        Find the corresponding web project according to the URL of the browser

    Sun company:

        Sun company is the maker of rules for the interaction between web servers and web projects 

        It has developed a Servlet interface, if programmers want the web server to manage their own resources, they must implement this interface 

    Java programmers who develop web projects:

        Write the implementation class of the Servlet interface, write the configuration file XML (binding the user's request path and the underlying java program together)

        The following three lines simulate an XML file




        The XML files of the web project are all saved in the form of similar path=resource (class name)

        When the user enters a resource, the web server can find the corresponding resource (value) according to the path (key)

        Then according to the class name (resource) through the reflection mechanism new object

3. Introduction to Servlet Specification

    1. Servlet macro is a specification, this specification comes from a kind of JavaEE specification

    2. Function:

        In the Servlet specification, specify the "dynamic resource file" development steps

        In the Servlet specification, specify the web server to call dynamic resource file rules.

        In the Servlet specification, specify the web server management dynamic resource file instance object rules.

4. Servlet interface implementation class

    1. The Servlet interface comes from the next interface of the Servlet specification, which exists in the jar package provided by the web server

    2. The lib file under the Tomcat server has a servlet-api.jar to store the servlet interface (javax.servlet.Servlet interface)

    3. According to the Servlet specification, the dynamic resource file that the web server can call must be a Servlet interface implementation class

5. Servlet interface implementation class development steps

    Step 1: Create a java class and let it implement the Servlet interface

        The subclass relationship of the Servlet interface is as follows

        Ancestor Interface Servlet------Grandpa Class GenericServlet (abstract)------Parent HttpServlet (abstract)------Subclass Java programmers write implementation classes

        The Servlet interface has five abstract methods (the most important is service)

        The GenericServlet class does not implement service, everything else is implemented

        The HttpServlet class implements the service method. In the service, the request side method name (get, post, etc.) is obtained through request.getMethod(), not reflection (Method is an attribute in the request class)

        Implementation classes written by java programmers need to rewrite specific doXXX methods

        According to this example, one of the functions of abstract classes can be seen:

            By means of abstract classes inheriting interfaces (abstract classes implement some of the abstract methods in interfaces), the degree of dependence of interface implementation classes on interfaces is reduced (interface implementation classes can directly inherit abstract classes that have implemented some methods, instead of inheriting everything. Interface not implemented)

        So instead of directly implementing the Servlet interface, the reason for inheriting the HttpServlet interface is mainly to simplify the development steps.

    Step 2: Rewrite the two methods in the parent class of HttpServlet, doGet or doPost

        The web server will find the corresponding implementation class according to the path name, create the object through reflection, and call the service method of this object actively by the web server

        In the implementation class, the doGet or doPost method is overridden, and the implementation class inherits the service method implemented by the HttPServlet class. The main function of the service method here is, 

        Obtain the method name of the requester through reflection and call the corresponding doXXX method     

    The third step: <register> the Servlet interface implementation class information to the web server

        In this way, the web server can find the corresponding implementation class according to the path and complete the related operations.

        web.xml path: web project file----web----WEB-INF---web.xml

        After finding the file, add the following:













 At this time, the request URL is: http://localhost:8081/web project name/one , the resource accessed is the oneServlet class The project name in IDEA can be changed in the Application context at the bottom of run----edit----Deployment

6. The life cycle of the servlet object (how the web server manages the web project)

    1. All servlet interface implementation class objects in a website (web project) must be created by the web server (reflection)

    2. By default, when the web server receives the first request of the current Servlet interface implementation class, it will automatically create an instantiated object of this Servlet interface implementation class

       In the case of manual configuration, you can require the web server to create an instantiated object of the class when it starts.

       Manually set in the web.xml configuration file






    3. During the running of the web server, only one instance object can be created for a Servlet interface implementation class

    4. When the web server is closed, all Servlet objects in the website are automatically destroyed

7. HttpServletResponse interface

1 Introduction       

  1. The HttpServletResponse interface comes from the Servlet specification and exists in servlet-api.jar in Tomcat

  2. The implementation class of the HttpServletResponse interface is provided by the web server

  3. The HttpServletResponse interface is responsible for writing the execution result of the doGet/doPost method into the response body and handing it to the browser

  4. Developers are used to calling the object instantiated by the HttpServletResponse interface the response object

2. Main functions

  1. Write the execution result into the response body in binary form (serialization and deserialization)


2. You can set the content-type attribute value of the response header to control the browser to use the corresponding compiler to compile the binary data of the response body into the corresponding text, picture, video, etc.       


At this time, the result displayed on the browser is not 50, but 2

 the reason:

out.writer(), you can write characters, strings, and ASCII codes into the response body

When the parameter is int, it will be regarded as ASCII code, and when the browser displays it, it will print the characters corresponding to the ASCII code

When the ASCII code is 50, the corresponding character is 2


Use out.print();

 Therefore, the out.print() method, writer() will be used in future development        


The result on the browser is: java

 Explain that the browser does not treat our response packet as HTML, but as ordinary text

 Reason: After receiving the response packet, the browser uses different compilers to compile the binary content in the response body according to the value of the content-type attribute of the response header

 In the default request, the value of our content-type attribute is "text", and the browser will use a text compiler to parse the binary value

 Solution: Before getting the output stream, re-assign the content-type attribute in the response header through the response object, so that the browser uses the corresponding binary compiler

Now that the HTML problem is solved, but there are still some results now?, grab a package to see the value of Content-type, Content-Type: text/html;charset=ISO-8859-1

Change character set


It shows that everything is normal, nice

At this time, grab a package and see that the Content-type is: text/html;charset=UTF-8 3. Set the location attribute of the response header, and assign a request address to location to control the browser to send requests to the specified server

After the browser receives the response packet, if it finds the location attribute in the response header, it will automatically send a request to the location specified by location through the address bar.

The sendRedirect method is used to remotely control the behavior of the browser

The three elements of the request are: request address, request method, and request parameters

Request parameters can be added after the URL by queryString


8. HttpServletRequest interface

1 Introduction

  1. The HttpServletRequest interface comes from the Servlet specification and exists in servlet-api.jar in Tomcat

  2. The implementation class of the HttpServletRequest interface is provided by the web server

  3. The HttpServletRequest interface is responsible for reading the information in the Http request protocol package when the doGet/doPost method is running

  4. Developers are used to calling the object instantiated by the HttpServletRequest interface the request object

  5. Inheritance interface HTTPServletRequest extends ServletRequest{}

  6. What information does HTTPServletRequest encapsulate?

Request method


Protocol version number

Form submission data


  1. One request corresponds to one HttPServletRequest

2. Function

  1. Can read the information in the request line (the first line of the request, including the request method, URL, Http protocol version) in the Http request protocol package


Print on the console:

        URL = http://localhost:8081/05/one

        method = GET

 You can also read the {URI} information in the {request line} through the request object

 request.getRequestURI(), read the URI, the return result is a string

URI: The precise location address of the resource file, there is actually no such attribute in the request line, it is actually a string intercepted according to the URL

 The format of this string is "/web project name/resource file name"

URI is used to allow the web server to locate the accessed resource


//3. Read {URI} information in {request line} through the request object

        //request.getRequestURI(), read URI information, and return the result as a String

        String uri = request.getRequestURI();

        System.out.println("URI = "+ uri);

 2. You can read the parameter information stored in the request header or request body in the Http request protocol package. Example: Create a static resource (HTML file) in a web project. This static resource is as follows:

            Access TwoServlet via hyperlink, and carry request parameters


When simulating access to a certain resource with parameter information, it can be seen that the parameters have username and password/two paths corresponding to the Servlet interface implementation class as follows:

The result printed on the console is: userName=Tompassword=123 The above example is to get the QueryString from the request header, and the following is to get it from the request body






The Servlet implementation class of this form submission path is as follows:

public class ThreeServlet extends HttpServlet {

            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            //Through the request object, read the parameter information of {request body}

            //The method is exactly the same as in the request header

            String value = request.getParameter("username");

            System.out.println("username = "+ value);



Type zhangsan on the form

The results displayed on the console are as follows:

username = zhangsan

 It can be seen that the code is the same regardless of whether the queryString information is obtained from the request header or the request body

 However, if the queryString in the post method has Chinese characters, garbled characters will appear

Reason: The browser sends the request in the Get method, and the parameters are stored in the request header. When the Http request protocol package reaches the web server (the content in the protocol package is binary), the first thing is to decode

The binary content in the request header is decoded by Tomcat, and UTF-8 is used by default

If the request is sent in Post mode, the parameters are stored in the request body. When the Http request protocol package reaches the web server (the content in the protocol package is binary), the first thing is to decode

The binary content in the request body is decoded by the request object (request). The request uses the [ISO-8859-1] character set by default, and garbled characters will appear in Chinese.

Solution: Before reading the content of the request body, notify the request object to use UTF-8 character set decoding

To be safe, we will rewrite the doGet and doPost methods, add the following code to specify the decoding method in the first two lines



  1. Can replace the browser to apply for resource file call to the Web server

Just redirect

3. Form submission data format

Example: username=admin&password=123&interest=sport&interest=music

As can be seen from the above example, the format of the form submission data information is similar to the format of key-value pairs

Key-value pairs can be abstracted as Map, but we found that interest corresponds to two values (a name in the check box may correspond to multiple values)

So the format of this Map is <String, String[]>

The above example Map format is as follows:

Map<String, String[]>


        key value

        username {"admin"}

        password {"123"}

        interest {"sport", "music"}

4. Common methods

Obtain the data submitted by the form data form, it will be automatically encapsulated in the request object, there is a Map<String, String[]> in the request object to store these data

String getParameter(String name)//Get the first element of the corresponding value(String[]) by key, this method is the most used

            Map getParameterMap()//Get the entire Map collection

            Enumeration getParameterNames()//Get all the keys of the entire Map collection

            String[] getParameterValues(String name)//Get the corresponding value through Key(String[]), this method is suitable for obtaining check box request information

Get path address

String getRemoteAddr()//Get the ip address of the client

            String getContexPath()//Get the context path (web project root path)

            String getMethod()//Get the request method

            String getRequestURI()//Get URI

            StringBuffer getRequestURL()//Get URL

            String getServletPath()//Get the Servlet path, where the path refers to the path related to web.xml and this Servlet implementation class (/xxx)

To store information in the request, you can refer to the following 5. What is the scope of HttpServletRequest

void setAttribute(String name, Object o)//Save data to the request range, name is key, o is value, similar to Map

            Object getAttribute(String name)//read data from the request range

            void removeAttribute(String name)//remove the data in the request range

Get the request forwarder, let the forwarder object point to a certain resource, the parameter here is the "/xxx" configured in the web.xml file

For details, please refer to the following 5. What is the scope of HttpServletRequest?

RequestDispatcher getRequestDispatcher(String path)

Conversation-related methods

Cookie[] getCookies()

            HttpSession getSession()

5. What is the scope of HttpServletRequest

 The object of HttpServletRequest type is usually named request, which represents this request

A request corresponds to a request object, the request range is very small, and the request can only complete the data transfer in the same request

Look at the following example: AServlet saves the object to the request, and then takes out the object

At this time, the browser prints: User{usercode='111', username='zhangsan'} If after the above operation is completed, let BServlet get the data from the request

The BServlet class is as follows:

 The result printed on the browser is: null

This shows that the request of these two Servlets is not an object. Solution: Forward

AServlet is changed to the following, BServlet remains unchanged

At this time, the browser displays: User{usercode='111', username='zhangsan'}

Note that the AServlet does not print to the browser, but the BServlet does, indicating that the data is obtained by forwarding the BServlet

Let's take a look at the packet and find that there is only one request, which means that there is only one request for forwarding

9. The life cycle of the request object and the response object

  1. After the web server receives the [Http Request Protocol Package] sent by the browser, it will automatically generate a [Request Object] and a [Response Object] for the current [Http Request Protocol Package]

  2. When the web server calls the doGet or doPost method, it is responsible for passing [request object] and [response object] as actual parameters to this method to ensure the correct execution of doGet/doPost

  3. When doGet or doPost has finished running, it means that this request has been processed, and the web server has generated an HTTP response protocol package.

So the life cycle of [request object] and [response object] runs through the whole process of a request processing

 [Request Object] parse out the content in [Request Protocol Package], [Response Object] is responsible for telling [Response Protocol Package] of the execution result of the doGet/doPost method

So the [request object] and [response object] are more like a messenger between the web server and the browser (or the user)

Okay, that s all for today s article, I hope it can help you who are confused in front of the screen