问题描述:
@WebServlet("/demo2")
public class HttpServletDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//加上这个super后为什么会出现405
super.doGet(req, resp);
System.out.println("doGet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
System.out.println("doPost");
}
}
当使用下面的代码访问
demo2
的时候,浏览器会返回如下信息:
问题原因
我们查看一下HttpServlet的部分源码:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
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(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
protected void doDelete(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_delete_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
可以看出来,如果我们在HttpServlet的实现类中使用super.doGet()
等这样类似的方法,就会出现405。这在源码中也有一定体现,即“http.method_delete_not_supported”
在HttpServlet
基本遵循模板方法模式,所有非重写HTTP方法返回此HTTP 405错误“不支持方法”。当你重写这样的方法,你应该不调用super方法,因为否则你将仍然得到HTTP 405错误。
解决办法
在我们正常实现的时候,不应该调用super.xxx()
方法,而是重新去实现这些方法,就ok了。