3

我的 servet 对于获取请求工作正常,但是当我调用 POST(使用 jquery ajax $.post)时,我收到错误 405(不允许方法)

这是我的代码:

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");
    }
}
4

2 回答 2

11

您确定您实际上覆盖了 doPost 方法吗?

签名如下所示:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, java.io.IOException

但是你像这样指定它:

public void doPost(HttpServletRequest request, HttpServletResponse response) 
           throws ServletException, IOException, IllegalStateException

我不确定这是否被允许: Overriding Java interfaces with new check exceptions

尝试以下步骤:

  1. 添加@Override 注解
  2. 删除 throws IllegalStateException (应该不是问题,因为它是运行时异常)
于 2013-11-17T09:07:13.203 回答
11

当我的方法调用时发生在我身上

"super.doGet(req, resp)" 或 "super.doPost(req, resp)" 。

在我从 doGet 和 doPost 中删除上面的超类调用后,它工作正常。

事实上,这些超类调用代码是由 Eclipse IDE 模板插入的。

于 2014-03-12T08:42:05.527 回答