报405:请求方式不支持
请求方式和Servlet里重写的方法不一样;如:
后端servlet重写doPost方法
public class Demo01Servlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="add" method="get">
名称:<input type="text" name="fname"/><br/>
价格:<input type="text" name="price"/><br/>
库存:<input type="text" name="fcount"/><br/>
备注:<input type="text" name="remark"/><br/>
<input type="submit" value="添加"/>
</form>
</body>
</html>
其他代码略
此时就会报405
本质原因
Servlet中有个核心方法service(),当有请求过来时service方法会自动响应(其实是tomcat容器调用的),然后在HttpServlet中我们会去分析请求的方式:到底是get、post、head还是delete等等。然后再去决定调用哪个do开头的方法。
而在HttpServlet中这些doGet()、doPost()等方法默认都是405的实现风格—要我们子类去实现对应的方法,否则就会报405错误。
因此,我们在新建Servlet时,我们才会考虑请求方法,从而决定重写哪个do方法,不重写就会执行父类方法
源码如下(以doPost()为例):
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(405, msg);
} else {
resp.sendError(400, msg);
}
}