先对访问URL有个概念:
1、html等静态内容若存放在web根目录下,则外界可直接访问:
服务器地址 / web项目根目录 / 静态内容
2、访问Servlet类中的动态资源,URL为:
服务器地址 / web项目根目录 / 资源目录
前提:html静态内容和Servlet类资源需要在同个位置,才可将html中的表单成功提交给Tomcat服务器
因此若在Servlet类中修改了资源目录,则html的访问目录也需要随之修改
一、/demo2
若有多个web项目,使用Tomcat部署时一般会为它们设置不同的web项目虚拟根目录,以避免项目覆盖。对于这种情况,通过以下方法来解决404:
Tomcat部署的Web项目根目录为/demo2
Web项目根目录 /demo2
Servlet类的资源路径 /test
访问html的路径 /demo2/test
对应代码:
@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>
访问Servlet类资源的URL:IP:port/demo2/test
访问html的URL:IP:port/demo2/login.html
(IP和port由个人决定)
二、/
Tomcat部署的Web项目根目录为/
Web项目根目录 /
Servlet类的资源路径 /test
访问html的路径 /test
对应代码:
@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>