POST 请求的 Java Servlet 返回错误 405(方法不允许)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19965253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Servlet return error 405 (Method Not Allowed) for POST request
提问by jcubic
My servet work fine for get requests but when I call POST (using jquery ajax $.post) I get error 405 (Method Not Allowed)
我的服务器可以很好地处理获取请求,但是当我调用 POST(使用 jquery ajax $.post)时,我收到错误 405(不允许的方法)
Here is my code:
这是我的代码:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class init extends HttpServlet {
public init() { }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("GET");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IllegalStateException {
response.setContentType("application/json");
ServletInputStream in = request.getInputStream();
PrintWriter out = response.getWriter();
out.print("POST");
}
}
采纳答案by Andreas Aumayr
Are you sure that you actually override the doPost Method?
你确定你真的覆盖了 doPost 方法吗?
The signature looks like this:
签名如下所示:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException
but you specify it like this:
但你指定它是这样的:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, IllegalStateException
I am not sure whether this is allowed: Overriding Java interfaces with new checked exceptions
我不确定这是否被允许: Overriding Java interfaces with new checked exceptions
Try the following steps:
尝试以下步骤:
- Add the @Override Annotation
- Remove the throws IllegalStateException (shouldn't be a problem as it is a runtime exception)
- 添加@Override 注解
- 删除 throws IllegalStateException(应该不是问题,因为它是运行时异常)
回答by sahan maldeniya
This happened to me when my method call
当我的方法调用时,这发生在我身上
"super.doGet(req, resp)" or "super.doPost(req, resp)" .
"super.doGet(req, resp)" 或 "super.doPost(req, resp)" 。
After i removed above super class calling from the doGet and doPost it worked fine.
从 doGet 和 doPost 删除上面的超类调用后,它工作正常。
Infact those super class calling codes were inserted by the Eclipse IDE template.
事实上,这些超类调用代码是由 Eclipse IDE 模板插入的。