POST请求的Java Servlet返回错误405(不允许使用方法)

我的服务可以很好地处理get请求,但是当我调用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");

}

}

回答:

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

签名如下所示:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, java.io.IOException

但您可以这样指定:

public void doPost(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException, IllegalStateException

请尝试以下步骤:

  1. 添加@Override注释
  2. 删除抛出的IllegalStateException(这不是问题,因为它是运行时异常)

以上是 POST请求的Java Servlet返回错误405(不允许使用方法) 的全部内容, 来源链接: utcz.com/qa/429808.html

回到顶部