HTTP 405 method GET/POST is not supported

来源:互联网 发布:overlay网络的价值 编辑:程序博客网 时间:2024/06/06 01:00

借鉴自:http://www.chawenti.com/articles/2852.html


问题描述:

JQuery使用Ajax请求后台Servlet出现405错误,不管是GET还是POST都会发生。

前台JS/JQuery代码:

function getServerTime(obj){var result;$.ajax({url:"ServerTimeService",data:{serverType:obj,xkey:"key"},dataType:"json",//这里使用text同样结果type:"GET",//这里POST同样结果asyc:false,complete:function(data,status){console.log("complete");if(status == "success"){console.log("success");result = data;}else{alert("获取服务器时间失败,是否使用本机时间代替?");//本次请求头的时间result = "err";}}})return result;}

后台Servlet处理:

@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {super.doGet(req, resp);doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {super.doPost(req, resp);String xkey=req.getParameter("xkey");String serverType = req.getParameter("serverType");PrintWriter out = resp.getWriter();if("APP".equals(serverType)){out.write("result: APP");}else if("DATA".equals(serverType)){out.write("result: DATA");}else{out.write("result: OTHER");}out.close();}

问题解决:

问题出现在doGet和doPost方法里,调用了父类super.doGet()、super.doPost()方法。不调用父类doGet(),doPost()方法即可解决改问题。

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

上文给出的解释:

1,继承自HttpServlet的Servlet没有重写对于请求和响应的处理方法:doGet或doPost等方法;默认调

用父类的doGet或doPost等方法;

2,父类HttpServlet的doGet或doPost等方法覆盖了你重写的doGet或doPost等方法;

不管是1或2,父类HttpServlet的doGet或doPost等方法的默认实现是返回状态代码为405的HTTP错误表示

对于指定资源的请求方法不被允许。

问题解决方法:

1,子类重写doGet或doPost等方法;

2,在你扩展的Servlert中重写doGet或doPost等方法来处理请求和响应时 不要调用父类HttpServlet的

doGet或doPost等方法,即去掉super.doGet(request, response)和super.doPost(request, response);


原创粉丝点击