一尘不染

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

tomcat

我的服务可以很好地处理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");
    }
}

阅读 835

收藏
2020-06-16

共1个答案

一尘不染

您确定确实覆盖了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(这不是问题,因为它是运行时异常)
2020-06-16