HTTP状态405 - Servlet中此URL不支持HTTP方法GET [英] HTTP Status 405 - HTTP method GET is not supported by this URL in Servlets
问题描述
为什么我得到 HTTP状态405 - 此方案中的URL 错误不支持HTTP方法GET.Well我在此之前完成了3个程序并且它们运行正常但是这显示了错误。
why am I getting HTTP Status 405 - HTTP method GET is not supported by this URL error in this Program.Well I completed 3 programs before this one and they just ran fine but this is showing the error.
package com.aamir;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet4 extends HttpServlet {
protected void service(HttpServletResponse res, HttpServletRequest req)
throws IOException, ServletException {
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<em>through out</em>");
System.out.println("through SOP");
}
}
web.xml
<web-app>
<servlet>
<servlet-name>Servlet4</servlet-name>
<servlet-class>com.aamir.Servlet4</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet4</servlet-name>
<url-pattern>/Servlet4</url-pattern>
</servlet-mapping>
推荐答案
这里,
protected void service(HttpServletResponse res, HttpServletRequest req) throws IOException, ServletException {
// ...
}
你换了 HttpServletResponse
和 HttpServletRequest
因此它与接口方法不匹配,因此它永远不会被容器调用。容器仍将调用 HttpServlet
模板类的原始 service()
方法,该方法又调用原始 doGet()
HttpServlet
模板类的方法,后者又返回HTTP 405错误。
You swapped HttpServletResponse
and HttpServletRequest
and hence it didn't match the interface method and hence it's never invoked by the container. The container will still invoke the original service()
method of the HttpServlet
template class which in turn calls the original doGet()
method of the HttpServlet
template class which in turn returns a HTTP 405 error.
将它们交换回正确的位置并添加 @Override
注释:
Swap them back to the right place and add @Override
annotation:
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
// ...
}
这样容器实际上会调用覆盖 service()
方法。正确使用 @Override
注释将导致错误方法签名上的编译错误。
This way the container will actually call the overriden service()
method. Using the @Override
annotation properly will cause a compilation error on wrong method signatures.
那就是说,你不应该' t需要覆盖 service()
方法,除非你打算生成另一个MVC控制器(除非出于业余爱好/学习目的,否则这个控制器有问题 - 另见设计模式基于Web的应用程序)。
That said, you shouldn't have the need to override the service()
method, unless you intend to homegrow another MVC controller (which is in turn questionable unless for hobby/learning purposes - see also Design Patterns web based applications).
这篇关于HTTP状态405 - Servlet中此URL不支持HTTP方法GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!