对于POST请求,Java Servlet返回错误405(方法不允许) [英] Java Servlet return error 405 (Method Not Allowed) for POST request

查看:2725
本文介绍了对于POST请求,Java Servlet返回错误405(方法不允许)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务对于获取请求很好,但是当我调用POST(使用jquery ajax $ .post)时,我收到错误405(方法不允许)

My servet work fine for get requests but when I call POST (using jquery ajax $.post) I get error 405 (Method Not Allowed)

这是我的代码:

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方法吗?

Are you sure that you actually override the doPost Method?

签名如下所示:

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

但是你这样指定:

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

我不确定是否允许这样做:
< a href =https://stackoverflow.com/questions/11835633/overriding-java-interfaces-with-new-checked-exceptions>使用新检查的异常覆盖Java接口

I am not sure whether this is allowed: Overriding Java interfaces with new checked exceptions

请尝试以下步骤:


  1. 添加@Override注释

  2. 删除抛出IllegalStateExceptio n(应该不是问题,因为它是运行时异常)

这篇关于对于POST请求,Java Servlet返回错误405(方法不允许)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆