1. What is a Servlet?

Back to 25 years ago, China was connected to the Internet less than two years ago. Computers in those days looked like this:

At that time, web technology was not very developed, we opened the browser can only browse somestaticPage, such as pictures, text messages, etc.

Over time, static pages are no longer enough for most users.

Users can’t just open a browser and see pictures and text, right? What if the user still wants to submit a form, click a button, and interact with the browser?

To solve the problem of dynamic interaction between users and browsers, in 1997, SUN (the company that invented the JDK) introduced Servlet technology.

Servlet is a Web component developed based on Java technology. It runs on the server side and is managed by the Servlet container. It is mainly used to process user requests and generate dynamic information.

A Servlet is simply a Java class written according to the Servlet specification.

We know that a class must have a main method in order to run independently, but the Servlet class does not have a main method. How does that work?

The answer is to run it in a servlet container.

You can think of servlets as apps, and a phone as a servlet container. The app cannot run alone, it must run on the phone.Because servlets have no main method and cannot run independently, they must be run inside a servlet container.

2. Install and use Tomcat

Tomcat 2.1 introduction

As mentioned earlier, servlets must run in a servlet container, and Tomcat is a container that can run servlets.

Why is Tomcat recommended? Because it’s free, open source and easy to use.

Tomcat responds to user requests as follows:

    1. The user sends an HTTP request to Tomcat(web server) through the browser.
    1. When Tomcat receives the request, it sends the request information to the Servlet container and gives the Servlet container oneThe request objectAnd aThe response object.
    1. The Servlet container loads the Servlet, creating one firstThe Servlet instance. Then tell the servlet instance: Hey! Boy, I have a user hereThe request objectandThe response objectYou take care of it.
    1. The Servlet instance fromThe request objectTake the request information from the client and act accordingly.
    1. The Servlet instance hands the result of the processing toThe response object, sent to the client through the response object.

Note:

  1. Request object: HttpServletRequest
  2. Response object: HttpServletResponse

2.2 Tomcat Installation and Configuration

Note: JDK must be installed and configured before Tomcat is installed.

  • Download decompression
Link: https://pan.baidu.com/s/1Ey-gg8tpHT9P-xNOUcrZmg extracted code: 1234Copy the code

  • Start tomcat

Go to the bin directory and double-click startup.shOpen your browser and type:

http://localhost:8080/
Copy the code

When the following screen appears, you have successfully installed!!

3. The Servlet specification

    1. The Servlet specification defines the development steps for dynamic resource files (essentially servlets).
    1. The Servlet specification defines the Tomcat servercallRules for servlets.
    1. The Servlet specification defines the Tomcat servermanagementRules for servlet instances.

Why are these specifications defined?

Because you’re writing a servlet class for Tomcat to manage and run, you have to listen to them. As the saying goes, where does a man not bow under a roof? So you have to follow the specifications that Tomcat specified.

4. Develop a Servlet

4.1 Create a JavaWeb project

Here we create a JavaWeb project using IDEA. Project Contents:

4.2 IDEA Configuring Tomcat

1. On the top menu bar, select Run and Edit Configuration.

2. Click +, select Tomcat Server, and select Local.

3. Select the local Tomcat installation directory for Application Server. The default Http port is 8080.4. Select Deployment and click on the right+Artifact selected.5. Select the Web project. The Application Context can be customized and is the default access path for our project.6. Write index. The JSP7. To run TomcatEnter the browser url:

http://localhost:8080/myProject/
Copy the code

4.3 development Servlet

1. Import the JAR package

Create a lib directory in the WEB-INF directory and add the Tomcat bin directory to the lib directoryservlert-api.jarPut it in the lib project.

2. Add the JAR package as a library to the project.

Note: Since the JAR package is the compiled Java code, this is equivalent to adding Java code under the Tomcat specification to the project.

Select the lib directory and right-click Add as a Library.3. Create a Servlet class

Servlet specification: To be managed by Tomcat, a new Servlet class must inherit the HttpServlet class from the Tomcat JAR package.

Create a Java class that inherits the HttpServlet superclass as a Servlet interface implementation class and override the doGet and doPost methods of the superclass.

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // This is used to process user get requests
        System.out.println("Get request received from user");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // This is used to process user POST requests
        System.out.println("Post request received from user"); }}Copy the code

4. Configuration web. XML

Why configure web.xml?

You created a servlet class according to the servlet specification, but Tomcat doesn’t know! So you need to tell big Brother.

Web. XML is Tomcat’s gatekeeper, where you need to register the Servlet interface implementation class information with the Tomcat server.

You need to register the name of the servlet class, the path of the project in which the class resides, and the request path.


      
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <! -- Hand over the Servlet interface implementation class to Tomcat
    <servlet>
        <servlet-name>userServlet</servlet-name> <! Servlet interface implementation class name -->
        <servlet-class>com.xxl.controller.UserServlet</servlet-class><! Declare servlet interface implementation class classpath -->
    </servlet>
    <servlet-mapping>
        <servlet-name>userServlet</servlet-name>
        <url-pattern>/user</url-pattern>  <! Set the request path for the Servlet class. The request path must start with a / -->
    </servlet-mapping>
</web-app>
Copy the code
  • Servlet-name: indicates the name of the servlet class.
  • Servlet-class: path to the project where the servlet class resides.
  • Url-pattern: Indicates the path of the servlet requested by the user.

5. Test

To run the project, enter:

http://localhost:8080/myProject/user
Copy the code

View console print:

Note: The browser directly enters the url, press enter to GET the request, as in HTML hyperlinks, for example:

<a href="/myProject/user">Click to access UserServlet</a>
Copy the code

6. Annotated development

Time from the keyboard sound of knocking code across, it seems that everything is calm, but one day it has an accident.

It was a dark afternoon when the Tomcat gatekeeper web. XML was reading the newspaper while eating melon seeds in the gatekeeper’s room.

That afternoon, 10,000 servlets came looking for web.xml to register.

Web. XML a look at this situation bengbu live! Immediately inform Tomcat’s senior officials.

Tomcat thought: “These ten thousand servlets have to be registered in monkey years? Forget it, don’t let them register. Let them wear a mark of their own that I recognize.”

So after Servlet 3.0, we don’t need to configure each servlet in web.xml, just add an annotation. Note format:

@webservlet (name = "servlet name ",value = "access path ")Or:@webservlet ("/ access path ") // The default name is the class name
Copy the code

Such as:

@WebServlet(name = "userServlet",value = "/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // This is used to process user get requests
       System.out.println("Ha ha ha ha ha HA I have notes on my head.");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // This is used to process user POST requests
        System.out.println("Post request received from user"); }}Copy the code

Or:

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // This is used to process user get requests
       System.out.println("Ha ha ha ha ha HA I have notes on my head.");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // This is used to process user POST requests
        System.out.println("Post request received from user"); }}Copy the code

The web.xml is empty:Even if web.xml doesn’t configure anything because we added itannotations, so Tomcat can also recognize it. Let’s request the servlet again and find that the request can also be successful.

To run the project, enter:

http://localhost:8080/myProject/user
Copy the code

note: The name and request path must be unique, otherwise Tomcat will not know which Servlet to give the user’s request to.

5. The Http protocol

5.1 introduction

Why learn the Http protocol?

Because only by knowing the Http protocol can you understand how information travels over the network, and you can understand what servlets do.

Htttp is mainly used in the client-server architecture. The browser, as an Http client, sends requests to the Web server through the URL. The commonly used Http requests include GET requests and POST requests. After the Web server processes the user’s request, it sends the response information to the client.

Information on the network is transmitted in binary form, which is encapsulated into Http packets. Http protocol packets include request packets and response packets.

5.2 the Http request

HTTP request message format mainly includes: request line, request header, request blank line, request data.

For example, the body of a GET request:

GET /login. HTML HTTP/1.1 Host: localhost User-agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; The rv: 60.0) Gecko / 20100101 Firefox 60.0 / Accept: text/HTML, application/XHTML + XML, application/XML. Q = 0.9 * / *; Q = 0.8 Accept - Language: useful - CN, useful; Q = 0.8, useful - TW; Q = 0.7, useful - HK; Q = 0.5, en - US; Q = 0.3, en. Q = 0.2 Accept - Encoding: gzip, deflate Referer: http://localhost/login.html Connection: keep-alive Upgrade-Insecure-Requests: 1Copy the code

The request line contains the request mode, REQUEST URL, and request Http version, for example:

GET/login. HTTP / 1.1 HTMLCopy the code

Request header format: Request header name: request header value, for example:

 Host: localhost
Copy the code

Here is a complete request header:

Host: localhost User-agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; The rv: 60.0) Gecko / 20100101 Firefox 60.0 / Accept: text/HTML, application/XHTML + XML, application/XML. Q = 0.9 * / *; Q = 0.8 Accept - Language: useful - CN, useful; Q = 0.8, useful - TW; Q = 0.7, useful - HK; Q = 0.5, en - US; Q = 0.3, en. Q = 0.2 Accept - Encoding: gzip, deflate Referer: http://localhost/login.html Connection: keep-alive Upgrade-Insecure-Requests: 1Copy the code

A request blank line is an empty line, which tells the server that there is no request header starting on the next line.

A GET request does not have a request body. Only a POST request has a request body. The body of the request is transmitted as a key-value pair.

5.3 the Http response

HTTP response message formats mainly include status lines, response headers, blank lines, and corresponding data. For example, here is a complete response body:

HTTP/1.1 200 OK Date: Wed, 22 Dec 2021 09:07:21 GMT Content-Type: text/ HTML; Charset =UTF-8 < HTML >< head></head> <body>Copy the code

Status line: HTTP version number, status code, and status message.

The first line, (HTTP/1.1), indicates that the HTTP version is 1.1, the status code is 200, and the status message is OK.

The second and third lines are response headers that specify additional information to be used by the client.

The fourth line is blank.

The final HTML code is the body of the response.

5.4 Differences between GET and POST

  • GET contains the request parameters in the URL, and POST passes the parameters through the request body.
  • GET is insecure because parameters are exposed directly to the URL and cannot be used to pass sensitive information.
  • GET requests have length limits on the parameters they pass in the URL, whereas POST has no limits.

6. Welcome page

We usually visit a website, is to enter a simple url, such as:

https://www.baidu.com
Copy the code

Instead of:

https://image.baidu.com/search/index?tn=baiduimage&ct=201326592
Copy the code

Because it’s too long a path for us to remember. Therefore, when users visit a website, we generally set a default page, such as baidu default home page:So how do we set up the default welcome page in our project?

Also configured in web.xml. Setting rules:

<welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
Copy the code

Then we need to create a welcome page in the Web or WebApp directory.

By default, the welcome page is displayed from top to bottom. If not configured, the welcome page is displayed from these files.

For example, we didn’t configure the welcome page when we created the project, but the content of index.jsp is displayed by default when the program runs.

Of course, we can also set up a custom welcome page, for example: login.html:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login.html</title>
</head>
<body>
<h1>Family! Family! Welcome to the login page!</h1>
</body>
</html>
Copy the code

Run the program:

7. HttpServletRequest

7.1 What is HttpServletRequest?

We send an Http request packet to the Http server through the browser, and the Http server automatically generates a request object and a response object for this Http request packet.

An HttpServletRequest represents a client request. All information in an HTTP request is encapsulated in this object. We can use this object to do the following:

  • Read the request information in the Http request protocol package
  • Request a resource file from the Http server

7.2 Obtaining Request Line Information

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 1. Obtain the [URL] information in the request line
        String url = request.getRequestURL().toString();
        // 2. Obtain the [method] information in the request line
        String method = request.getMethod();
        // select * from [url = "/ url/url "];
        String uri = request.getRequestURI();
        
        System.out.println("Request URL:" + url);
        System.out.println(Request method: + method);
        System.out.println("Request URI:" + uri);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // This is used to process user POST requests
        System.out.println("Post request received from user"); }}Copy the code

To run the project, enter:

http://localhost:8080/myProject/user
Copy the code

Console print result:

7.3 Obtaining The Parameters of the Request Header

We use the following method to obtain the parameter information of the request header:

String parameter = request.getParameter(" Parameter name ");Copy the code

7.3.1 Obtaining Parameters of the GET Request Header

First we append the request parameters to the browser request path. Multiple parameters are separated by &, for example:

http://localhost:8080/myProject/user? Name = a Rebus &age=23
Copy the code

Modify code:

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get the name parameter of the request header
        String name = request.getParameter("name");
        // Get the age parameter of the request header
        String age = request.getParameter("age");
        System.out.println("name: "+name);
        System.out.println("age: "+age);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // This is used to process user POST requests
        System.out.println("Post request received from user"); }}Copy the code

Run the program to view the printed information on the console:

7.3.2 Obtaining the Parameters of the POST Request Header

Let’s modify the default welcome page login. HTML by adding a form message:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login.html</title>
    <style>
        div {
            width: 300px;
            height: 300px;
            margin: 0 auto;
        }

    </style>
</head>
<body>
<div>
    <form action="/myProject/user" method="post">
        <lable>Name:</lable>
        <input type="text" name="name"></br>
        <lable>Password:</lable>
        <input type="password" name="password"></br>
        <input type="submit" value="Login">
    </form>
</div>
</body>
</html>
Copy the code

Modify the servlet code:

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // This is used to process user get requests
        System.out.println("Get request received from user");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get the name parameter of the POST request
        String name = request.getParameter("name");
        // Get the password parameter for the POST request
        String password = request.getParameter("password");
        System.out.println("name: "+name);
        System.out.println("password: "+password); }}Copy the code

Enter the information in the browser page, the password is 123456, and click the login button:View the printed information on the console:

7.3.3 Troubleshoot garbled Parameters in POST Requests

In the above example, we found that English and numbers can be output normally, but Chinese characters are garbled. Why?

When a browser sends a request in GET mode, the request parameters are stored in the request header and the Http server decodes the request protocol packet.

Tomcat is responsible for decoding it. Because Tomcat uses the UTF-8 character set by default, which can interpret all countries’ characters, even Chinese characters are not garbled.

When a browser sends a request in POST mode, the request parameters are stored in the request body, and the Http server decodes the request protocol packet.

The request object request is responsible for decoding the contents of the request body. Request uses the ISO-8859-1 character set by default. This character set is an Eastern European character set, so Chinese characters will be garbled.

In order to solve the problem of garbled characters in Post request mode, the request object should be decoded using UTF-8 character set.

 request.setCharacterEncoding("utf-8");
Copy the code

Let’s rewrite the servlet code:

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // This is used to process user get requests
        System.out.println("Get request received from user");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Tomcat notifies the request object, using the UTF-8 character set to override the request body
        request.setCharacterEncoding("utf-8");
        // Get the name parameter of the POST request
        String name = request.getParameter("name");
        // Get the password parameter for the POST request
        String password = request.getParameter("password");
        System.out.println("name: "+name);
        System.out.println("password: "+password); }}Copy the code

Enter information on the browser page and click the login button to view the printed information on the console:

8. HttpServletResponse

8.1 What is HttpServletRequest?

HttpServletResponse is a response object that does the following:

  • Writes the result in binary form toResponse body
  • Set the response headercontent-typeAttribute values
  • Set the response headerlocationProperty that lets the browser send a request to the specified Http server.

8.2 Send the Response result to the Browser

We put the response result into the response body of the Http response package, and then compile and parse the binary content of the response body in the browser to display its contents.

Syntax format:

PrintWriter writer = response.getWriter(a); writer.println(Response result content);Copy the code

Let’s modify the servlet code:

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String result1 = "<h1>2022: Where there is a well,there is a way<h2>";
        String result2 = "Seabird and fish fell in love. It was an accident.";
        PrintWriter writer = response.getWriter();
        writer.println(result1);
        writer.println(result2);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // This is used to process user POST requests
        System.out.println("Post request received from user"); }}Copy the code

To run the project, enter:

http://localhost:8080/myProject/user
Copy the code

View the browser response:

8.3 Setting the Response Header Content-Type

From the example above, we can see that English and numbers work, but Chinese characters are garbled. We can format the response header content-Type so that the browser can output Chinese characters.

Set the syntax format of content-Type:

 response.setContentType("content-type format ");Copy the code

Let’s modify the servlet code:

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String result1 = "<h1>2022: Where there is a well ,there is a way<h2>";
        String result2 = "Seabird and fish fell in love. It was an accident.";
        
        // Format the content-type of the response header
        response.setContentType("text/html; charset=utf-8");
        
        PrintWriter writer = response.getWriter();
        writer.println(result1);
        writer.println(result2);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // This is used to process user POST requests
        System.out.println("Post request received from user"); }}Copy the code

To run the project, enter:

http://localhost:8080/myProject/user
Copy the code

View the browser response:

8.4 Sending requests to the Specified Http Server

We can set the location property in the response header to redirect the browser to the specified url. Syntax format:

 response.sendRedirect(" site ");Copy the code

Let’s modify the servlet code:

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. If the location attribute is found in the HTTP response header after the browser receives the HTTP response packet
        // 2. Automatically send a request to the site specified by location via the address bar
        // 3. The sendRedirect method controls the browser request behavior
        response.sendRedirect("http://www.baidu.com");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // This is used to process user POST requests
        System.out.println("Post request received from user"); }}Copy the code

To run the project, enter:

http://localhost:8080/myProject/user
Copy the code

View the browser response:

9. Redirection and request forwarding

9.1 Servlets access each other

Suppose one day you say to an Http server: I want to eat braised chicken. The resulting visit scenario looks like this:

Later you completely broke the defense: “I want to eat a braised chicken, need to visit so many times? What a stupid website, no more!”

So to improve the user experience, the servlet specification defines rules for multiple servlets to call each other.

No matter how many servlets are involved in the request, the user only needs to make a request to the browser once, the servlets collaborate with each other, and the user gets the response.

There are two rules for multiple servlets to call each other:

    1. Redirect the solution
    1. Request forwarding solution

9.2 the redirection

  1. Principle:

Users first access oneServlet through a browser, but oneServlet doesn’t solve their problems. OneServlet then writes the TwoServlet’s access address to the Location property of the response header.

Once the browser gets the Http response, it sends the request again to the twoServlet in the Http server based on the value of Location in the response header. The twoServlet then handles the user’s request.

Actually redirection is equivalent to you go looking for Liu Bei to borrow money, Liu Bei says I have no money you go looking for Cao Cao. Then you went to Cao Cao to borrow money and finally got it.

  1. Features:
  • The browser sends at least two requests. Only the first request is sent by the user through the browser, and the rest are automatically sent by the browser.
  • The request is redirected in GET mode.
  • The browser address bar changes because the requested address changes.
  • In addition to accessing resources within the HTTP server, you can also access external Web site resources. Such as Baidu.
  • The browser accesses the server multiple times, increasing the user waiting time.
  1. implementation
 response.sendRedirect(" site ");Copy the code
  1. case

New OneServlet

@WebServlet("/one")
public class OneServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.sendRedirect("/myProject/two");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

New TwoServlet

@WebServlet("/two")
public class TwoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("I'm twoServlet, and I'll solve your problem!");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

Run the project and use a browser to access OneServlet:

http://localhost:8080/myProject/one
Copy the code

View the browser response:

9.3 Request Forwarding

Principle 1.

Users first access oneServlet through a browser, but oneServlet doesn’t solve their problems. OneServlet then passes the Request object and response object to TwoServlet, which then processes the user’s request.

Actually,Forward requestsJust like you go to Borrow money from Liu Bei, liu Bei has no money in his pocket, but Liu Bei is a loyal man, he takes you to borrow money from Cao Cao, and finally you borrow money from Cao Cao.

Characteristics of 2.

  • During request forwarding, the browser sends the request only once.
  • If a request is forwarded within an HTTP server, only internal resources can be requested.
  • During request forwarding, the browser sends only one Http request protocol packet. So all servlets participating in this request share the same request protocol package.
  • The browser address bar does not change because the request is forwarded internally by the Http server.

3. Implementation method

RequestDispatcher requestDispatcher = request.getRequestDispatcher(" Next servlet request path "); // Assign the request object and response object of the Http request package to the next servlet requestDispatcher.forward(request,response);
Copy the code

Case 4.

Only change the OneServlet

@WebServlet("/one")
public class OneServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Since the request forwarding is done internally by the HTTP server, it is equivalent to calling the resources of the same project, so it is ok to write the access path of the servlet directly
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/two");
        // Pass the request object and response object of the Http request packet to the next servlet
        requestDispatcher.forward(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

Run the project and use a browser to access OneServlet:

http://localhost:8080/myProject/one
Copy the code

View the browser response:Summary: redirectedheavyThe browser sent the request to the server more than twice. The request forwarding happens inside the server, and the browser only requests it once.

10. Data sharing between servlets

Data sharing: After the first Servlet processes the request, the data is handed over to the second Servlet for use.

The Servlet specification provides four ways to address data sharing.

10.1. The ServletContext

1. Global scope

The ServletContext object is a global scoped object. A global scope object is a common area in the classroom where the teacher puts some common items and all students (servlets) can use them.

2. Usage

Adds shared data to the global scope object

// 1Get the global scope object ServletContext ServletContext = request.getServletContext(a); //2. Add shared data to the global scope object servletContext.setAttribute("key",value);
Copy the code

Gets shared data from the global scope object

// 1Get the global scope object ServletContext ServletContext = request.getServletContext(a); //2. Gets shared data from the global scope objectObject value = servletContext.getAttribute("key");
Copy the code

3. Case modification OneServlet

@WebServlet("/one")
public class OneServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. Get the global scope object
        ServletContext servletContext = request.getServletContext();
        // 2. Add shared data to the global scope object
        servletContext.setAttribute("info"."May you pass your final exams this year! Wish this year to take an examination of one's deceased father's grind, take an examination of male you certainly shore!");
        // 3. Redirect
        response.sendRedirect("/myProject/two");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

Modify TwoServlet

@WebServlet("/two")
public class TwoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. Get the global scope object
        ServletContext servletContext = request.getServletContext();
        // 2. Get shared data from the global scope object
        String info = (String)servletContext.getAttribute("info");
        response.setContentType("text/html; charset=utf-8");
        // 3. Send the shared data to the browser
        response.getWriter().println(info);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

Run the project and use a browser to access OneServlet:

http://localhost:8080/myProject/one
Copy the code

View the browser response:

10.2. The Cookie

1. Introduction

A Cookie is an object in the Servlet specification. If two servlets are from the same web site, you can use Cookie objects to share data.

Principle 2.

The user requests OneServlet, and OneServlet creates a Cookie to store data related to the current user. The OneServlet executes, writes the Cookie to the response header and returns it to the current browser.

After the browser retrieves the Http response package, the cookie information is stored in the browser’s cache.

After some time, the user accesses TwoServlet through the same browser. The browser writes Cookie information from the cache to the request header of the Http request package.

At this point TwoServlet can retrieve the OneServlet shared data by reading the cookie information in the request header.

In fact, the principle of Cookie is like when you (browser) go to the gym for the first time (Http server), the gym staff gives you a membership card (Cookie). Next time you go to this gym, the staff will know who you are when they get their membership card.

3. Usage

Create cookies to save shared data

// 1. Create a cookie object to save the shared data
Cookie cookie = new Cookie("key"."value");
// 2. Write the cookie information to the response header and hand it to the browser
response.addCookie(cookie);
Copy the code

Obtaining Shared Data

// 1. Call the request object to get the Cookie information returned by the browser from the request header
Cookie cookies[] = request.getCookies();
// 2. Iterate over the data to obtain the key and value of the cookie
for(Cookie cookie:cookies) {
    // 3. Obtain the key value
    String key = cookie.getName();
    // get the value of value
    String value = cookie.getValue();
}
Copy the code

4. Case modification OneServlet

@WebServlet("/one")
public class OneServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. Create a cookie object to save the shared data
        Cookie cookie = new Cookie("name"."jay");
        // 2. Write the cookie information to the response header and hand it to the browser
        response.addCookie(cookie);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

Modify TwoServlet

@WebServlet("/two")
public class TwoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. Call the request object to get the Cookie information returned by the browser from the request header
        Cookie cookies[] = request.getCookies();
        // 2. Iterate over the data to obtain the key and value of the cookie
        for(Cookie cookie:cookies) {
            // 3. Obtain the key value
            String key = cookie.getName();
            // get the value of value
            String value = cookie.getValue();
            System.out.println("key: "+key+" value: "+value); }}@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

To run the project, visit OneServlet first:

http://localhost:8080/myProject/one
Copy the code

Visit TwoServlet again:

http://localhost:8080/myProject/two
Copy the code

View the console print result:

Note:

  • A cookie is equivalent to a map.
  • Only one key-value pair can be stored in a cookie.
  • The key and value of a key-value pair can only be strings.
  • The key in a key-value pair cannot be Chinese.

5. Cookie destruction time

By default, Cookie objects are stored in the browser’s cache. So as soon as you close the browser, the Cookie object is destroyed.

In order to prolong the Cookie survival time, we can store the Cookie information on the hard disk of the local computer and set the Cookie survival time.

Cookies will not be destroyed if the browser or server is closed during the lifetime. When the keepalive time is up, the Cookie is automatically deleted.

Set the lifetime of the Cookie on the hard disk:

Cookie cookie = new Cookie("name"."jay");
// The cookie lives on the hard disk for 2 minutes
cookie.setMaxAge(120); 
Copy the code

10.3. The Session

1. Introduction

Session is an object in the Servlet specification. If two servlets are from the same web site, you can use the Session object to share data. We tend to call a Session a Session object.

Principle 2.

The user requests OneServlet, and OneServlet creates a Session object to store data associated with the current user. The OneServlet executes and saves the Session to the Http server’s memory.

The user then accesses TwoServlet through the same browser. TwoServlet can then retrieve the shared data provided by OneServlet through a Session in the Http server’s memory.

Sessions can be thought of as a safe on the server side.

3. Usage

Create a Session to save shared data

// 1HttpSession Session = Request.getSession(a); //2. Save the data to the server memory (safe) session.setAttribute("key", shared data);Copy the code

Obtaining Shared Data

// 1HttpSession Session = request.getSession(a); //2. Get shared data from sessionObjectShared data = session.getAttribute("key");
Copy the code

Case 4.

Modify OneServlet

@WebServlet("/one")
public class OneServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. Create session objects
        HttpSession session = request.getSession();
        // 2. Save data to server memory (safe)
        session.setAttribute("key".123);

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

Modify TwoServlet

@WebServlet("/two")
public class TwoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. Obtain session
        HttpSession session = request.getSession();
        // 2. Obtain shared data from session
        Object info = session.getAttribute("key");
        System.out.println("Retrieving information from session:"+info);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

To run the project, visit OneServlet first:

http://localhost:8080/myProject/one
Copy the code

Visit TwoServlet again:

http://localhost:8080/myProject/two
Copy the code

View the console print result:Note:

  • The HttpSession object can store any type of shared data.
  • An HttpSession is like a map collection, so it can store any amount of shared data.

10.4. It

1. Introduction

In the same site, two servlets are called by request forwarding because they share the same request protocol package, so the servlets share the same request object. Therefore, you can use this request object to share data between the two servlets.

This request object is called the request scope object.

2. Usage

Use the request object to save the shared data

// The data type can be any type req.setAttribute(" key ", data);Copy the code

Use the request object to get the shared data

// Get shared data from the request objectObjectData = the req.getAttribute("key");
Copy the code

Case 3.

Modify OneServlet

@WebServlet("/one")
public class OneServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Use the request object to save shared data
        request.setAttribute("info"."All the way north, away from the season of thee.");
        // Request forwarding
        request.getRequestDispatcher("/two").forward(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

Modify TwoServlet

@WebServlet("/two")  
public class TwoServlet extends HttpServlet {  
    @Override  
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // Get shared data from the request object
  Object info = request.getAttribute("info");  
  response.setContentType("text/html; charset=utf-8");  
  response.getWriter().println(info);  
  }  
    @Override  
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}}Copy the code

Run the project and use a browser to access OneServlet:

http://localhost:8080/myProject/one
Copy the code

View the browser response:

11. Filter

1. Introduction

Filter is an interface in the Servlet specification that tells Tomcat to intercept user requests before invoking a resource file.

For example, if users want to see their shopping cart information before they have logged on to the website, they need to intercept the user’s request.

2. Usage

  • Create a Filter class to implement doFilter in the filter interface.
  • Configure the filter class in web.xml
 <! -- Configure filter -->
<filter>
  <filter-name>userFilter</filter-name>
  <filter-class>com.xxl.filter.UserFilter</filter-class>
</filter>
<! Tell Tomcat which resource file needs to be blocked by the current filter when the user calls it.
<filter-mapping>
  <filter-name>userFilter</filter-name>
  <url-pattern>Intercept path</url-pattern>
</filter-mapping>
Copy the code

Case 3.

New UserFilter

public class UserFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {}}Copy the code

Put a picture of a beautiful woman in the project:Configure UserFilter in web.xml to block the photo.


      
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <! -- Configure filter -->
    <filter>
        <filter-name>userFilter</filter-name>
        <filter-class>com.xxl.filter.UserFilter</filter-class>
    </filter>
    <! Tell Tomcat which resource file needs to be blocked by the current filter when the user calls it.
    <filter-mapping>
        <filter-name>userFilter</filter-name>
        <url-pattern>/girl.jpg</url-pattern>
    </filter-mapping>
</web-app>
Copy the code

Refine the UserFilter code to determine if the age parameter is older than 18.

public class UserFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. Obtain request parameters by intercepting request objects
        String age = servletRequest.getParameter("age");
        // 2. If the age is legal
        if (Integer.parseInt(age) > 18) {
            // 3. Return the interception request object and response object to Tomcat, which then invokes the resource file and releases it
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            servletResponse.setContentType("text/html; charset=utf-8");
            servletResponse.getWriter().println("Look at that beautiful woman! Do your homework!"); }}}Copy the code

Running results:

4. Annotated development

No need to configure it in web.xml, annotate the filter class directly:

@WebFilter(filterName = The filter name "",urlPatterns = "Intercept path")
Copy the code

Modify the UserFilter code:

@WebFilter(filterName = "userFilter",urlPatterns = "/girl.jpg")
public class UserFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. Obtain request parameters by intercepting request objects
        String age = servletRequest.getParameter("age");
        // 2. If the age is legal
        if (Integer.parseInt(age) > 18) {
            // 3. Return the interception request object and response object to Tomcat, which then invokes the resource file and releases it
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            servletResponse.setContentType("text/html; charset=utf-8");
            servletResponse.getWriter().println("Look at that beautiful woman! Do your homework!"); }}}Copy the code

It works the same way.