Tomcat/Servlet submit form 404 solution

First, there is a concept of access URL:
1. If static content such as html is stored in the web root directory, it can be directly accessed by the outside world:
server address/web project root directory/static content
2. To access dynamic resources in the Servlet class, the URL is :
Server address/web project root directory/resource directory

Prerequisite: HTML static content and Servlet resources need to be in the same location before the form in html can be successfully submitted to the Tomcat server

Therefore, if the resource directory is modified in the Servlet class, the html access directory also needs to be modified accordingly

One, /demo2

If there are multiple web projects, different web project virtual root directories are generally set for them when deploying with Tomcat to avoid project coverage. In this case, use the following methods to solve 404: The
root directory of the Web project deployed by Tomcat is /demo2

Web项目根目录	   	 /demo2
Servlet类的资源路径   /test
访问html的路径        /demo2/test

Corresponding code:

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("Submitted by post");
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/demo2/test" method="post">
        <input name="username">
        <input type="submit" value="Go">
    </form>
</body>
</html>

URL for accessing Servlet resources: IP:port/demo2/test
URL for accessing html: IP:port/demo2/login.html
(IP and port are determined by individuals)

two,/

The root directory of the Web project deployed by Tomcat is /

Web项目根目录	    /
Servlet类的资源路径  /test
访问html的路径       /test

Corresponding code:

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        System.out.println("Submitted by post");
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/test" method="post">
        <input name="username">
        <input type="submit" value="Go">
    </form>
</body>
</html>

Guess you like

Origin blog.csdn.net/HellHellNo/article/details/115370973