报错场景

​ 在写好一个简单的登录页面,login.html和一个servlet类后。启动tomcat就报如下错误。

image-20211205120621813

大概意思无法启动组件LifecycleException。

代码如下

login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/httpExam/login" method="post">
<div> <input name="username" value=""/></div>
<div> <input name="password" value=""/></div>
<button type="submit"> 提交</button>
</form>
</body>
</html>

LoginServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
@WebServlet("login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("asdrwq");

}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doget");
}
}

找错过程

​ 于是我开始怀疑①是不是servlet相关的类没有引入,发现HttpServlet类可以点进去。就排除了①的可能。

​ 第②种可能是我login.html的form里的action请求写错了或LoginServlet.java的接收路径写错。编译时报错说明tomcat在初始化的时候有问题,于是就百度发现是我在LoginServlet里的@WebServlet注解没有给参数前面加【/】。我没有用SpringMVC中的@RequestMapping注解,我发现以前写的所有关于处理请求的注解@RequestMapping,@GetMapping@PostMapping等url前面都加了/。为什么要加url前面加/呢,我不知道哈哈只知道这样写就对了。

所以正确的写法是 @WebServlet(“/login”)

参考资料https://blog.csdn.net/xieminglu/article/details/102865450