Introduction to Servlet

What are Servlets?

The first Servlet program: Hello World

1. Create a project

Create a Maven project using IDEA

  1. New Project → Maven

insert image description here

  1. Enter the project name and select the directory where the project will be stored

insert image description here

After the project is created, check the

  1. Whether the Maven project content is marked red

insert image description here

  1. With or without properties

insert image description here

2. Introduce dependencies

After the Maven project is created, a pom.xml file will be automatically generated; we need to introduce the jar package that the Servlet API depends on in pom.xml

  1. First , search for the servlet in the central repository:

insert image description here

  1. Select the version, generally use version 3.1.0

The Servlet version should match Tomcat.
If we use Tomcat 8.5, then we need to use Servlet 3.1.0 to click to query the version correspondence

insert image description here

  1. Copy the xml provided in the central repository to the pom.xml of the project

Note here that xml needs to be pasted in the dependencies tag

insert image description here
After modification, namely:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Servlet-Study</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

If " javax.servlet-api " and " 3.1.0 " are marked in red, open Maven on the right, click refresh, and the dependency success will be displayed below
After modifying pom.xml, you must refresh the Maven panel to take effect

insert image description here

3. Create a directory

We found that when the project is created, IDEA will automatically create some directories for us:

insert image description here
Explanation:
src: Indicates the directory where the source code is located.
main/java: Indicates the root directory of the source code. Subsequent created .java files are placed in this directory.
main/resources: Indicates the directory where some resource files of the project are located
test/java: Indicates The root directory of the test code

In addition to the above automatically generated directories, we also need to create some new directories/files:

  1. Create the webapp directory

In the main directory, juxtaposed with the java directory, create a webapp directory (note that it is not webapps)

insert image description here
insert image description here

  1. Create the web.xml file

Then create a WEB-INF directory inside the webapp directory and create a web.xml file under it

insert image description here
insert image description here

  1. Write web.xml
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>Archetype Created Web Application</display-name>
</web-app>

Above, the environment of the web project is configured, and the development of servlet can be carried out

4. Write code

Create a class HelloServle in the java directory
to rewrite doGET as an example:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
//        super.doGet(req, resp);  这段代码要删掉,否则会报错
    }
}

Servlet development is to process requests and return responses through standard Servlet standard APIs

  1. WebServlet indicates that the current class is a Servlet class that needs to process requests and responses
  2. How to know that a request needs to be processed by the current servlet class? Request line (request method, URL):
    access path: defined in @WebServlet (after writing the path, you can know that each path is processed by the current servlet class and this program)
    Note: the path starts with /, otherwise An error will be reported; a virtual path is defined (maybe there is no corresponding file for this path)
  3. Inherit HttpServlet: handle the Http protocol
  4. Rewrite the doXXX method of the parent class: XXX is the service method provided (the same method needs to be used when requesting)
  5. HttpServletResponse represents the HTTP response, and the response object is constructed in the code (the status code of the construction response, header, body, etc.)
  6. resp.getWriter() will get a stream object, through which some data can be written, the written data will be constructed into the
    body part of an HTTP response, and Tomcat will convert the entire response into a string, through the socket write back to the browser

insert image description here

Although the above code has only a few lines, it contains a huge amount of information:

  1. The code is no longer entered through the main method. The main method has been included in Tomcat. The code we write will be
    called by Tomcat at the right time. At this time, the code we write is not a complete program, but Tomcat A small piece of logic for this program
  2. Thinking: Can any class be called by Tomcat? What conditions must be met to be called?
    Mainly meet the following three conditions:
    a) The created class needs to inherit from HttpServlet
    b) This class needs to use the @WebServlet annotation to associate an HTTP c) This class
    needs to implement the doXXX method.
    When these three conditions are met, Tomcat can find this class and call it at the right time

5. Packager

Use Maven to package, open the Maven window, expand Lifecycle, double-click the package to package

insert image description here
Successful packaging:

insert image description here
After the packaging is successful, you can see that a jar package is generated in the target directory:

insert image description here
The above jar package is not what we need, Tomcat needs to recognize another war package format; in addition, the name of the jar package is too complicated, I hope to change the name to be simpler

The difference between war package and jar package:
.jar
package is the result of ordinary java program packaging, which contains some .class files.
war package is a java web program, which contains not only .class files, but also HTML, CSS, JavaScript, images, and other jar packages; only in war package format can they be recognized by Tomcat

The origin of the jar package name: (Servlet-Study-1.0-SNAPSHOT.jar)

It is equivalent to splicing artifactId and version together ( the default packaged file name is relatively long, which is product name-version number )

insert image description here
How to pack the war package? ?
Add a packing tag in pom.xml, indicating that the packaging method is to make a war package

insert image description here
At this time, double-click the package to open the war package:

insert image description here

How to change the war package name? ?
Add a build tag in pom.xml, and a built-in finalName tag, indicating that the name of the war package to be printed is HelloServlet

insert image description here
At this time, open the Maven panel again, first clean, and then double-click the package again to package:

insert image description here

Attach the complete pom.xml code:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Servlet-Study</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- servlet依赖包: 官方提供的标准  -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <!-- 开发编译时需要这个依赖包,运行时不需要 -->
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>HelloServlet</finalName>
    </build>

</project>

6. Deployment program

Package the web application into a compressed war file, and then copy the war package to Tomcat's webapps directory

insert image description here
insert image description here

Then start Tomcat, and Tomcat will automatically decompress the war package:

insert image description here

7. Verification procedure

At this time, visit http://127.0.0.1:8080/ServletHello/hello through the browser, and you can see the result:

insert image description here
Note: The PATH in the URL is divided into two parts; where HelloServlet is the Context Path, hello is the Servlet Path

insert image description here

View through fiddler packet capture:

insert image description here

Simplify deployment

The above-mentioned deployment of heatstroke prevention is cumbersome. We can simplify the deployment method by installing and configuring plug-ins

Install the Smart Tomcat plugin

  1. open settings

insert image description here

  1. Select Plugins, select Marketplace, search for "tomcat", and click "Install"

Note: The installation process must be connected to the Internet

insert image description here

  1. After the installation is complete, restart IDEA

Configure the Smart Tomcat plugin

  1. Click "Add Configuration" in the upper right corner

insert image description here

  1. Select "Smart Tomcat" on the left

insert image description here

  1. Fill in a name in the Name column
    and select the directory where Tomcat is located in the Tomcat Server column. Other options do not need to be modified

insert image description here
insert image description here

  1. After clicking OK, the upper right corner becomes

insert image description here
Click the green , IDEA will automatically compile, deploy, and start the process of Tomcat

At this point, the Tomcat log will be output in the IDEA console, and you can see that there are no more garbled characters now:
.insert image description here

  1. Visit the page
    You can click on this blue URL to jump directly

insert image description here
However, I get a 404 because the resource accessed at / does not exist:

insert image description here
After manually adding the specific path to be accessed:

Pay attention to the access path here

insert image description here

access error

404

404 indicates that the resource accessed by the user does not exist, most likely the path of the URL is written incorrectly

Error example 1: write less Context Path, access the server through /hello

insert image description here
Error example 2: The Servlet Path is written less, and the server is accessed through /HelloServlet

insert image description here

405

405 indicates that the method is not supported (the corresponding HTTP request method is not implemented)

Error instance: The doGet method is not implemented

@WebServlet("/post")
public class postServlet extends HttpServlet {
    
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        resp.getWriter().println("post");
    }
}

Restart the Tomcat server and visit it in the browser, you can see:

insert image description here
(The access method of the browser address bar is GET by default)
Enter the URL directly in the browser address bar, and an HTTP GET request will be sent; at this time, the postServlet class will be found according to the path /Servlet-Study/post and try to call the doGet method of postServlet; but if the doGet method is not implemented, it will The above phenomenon occurs

500

It is often caused by an exception thrown in the Servlet code

Error instance:

@WebServlet("/error")
public class ErrorServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        int i = 1;
        int k = i / 0;
        resp.getWriter().println("error");
    }
}

Restart the Tomcat server and revisit the page, you can see:

insert image description here

There is already a specific exception call stack on the page.
The exception information has already indicated that the code that caused the exception is line 13 of ErrorServlet.java.

  • int k = i / 0;

blank page

Error instance:

@WebServlet("/empty")
public class EmptyServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("empty");
    }
}

Restart the Tomcat server and revisit the page, you can see:
insert image description here
You can use fiddler to capture packets and view, the content in the response body is "empty data"

insert image description here

can't access this site

Generally, Tomcat fails to start.

Error example: Servlet Path is written incorrectly

@WebServlet("empty")
public class EmptyServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("empty");
    }
}

Restart the Tomcat server and revisit the page, you can see:

insert image description here
visit website:

insert image description here
Note: One thing to check is whether there is an error
Servlet path when starting Tomcat. It must start with /, and an error will also be reported if there is a space in front of /;In a webapp, the path of Servlet must be unique

insert image description here

Guess you like

Origin blog.csdn.net/m0_47988201/article/details/123028543