在servlet3.0开始,配置servlet有两种方式。
- 在servlet类中使用@WebServlet注释的进行配置(新方式)
- 通过在web.xml文件中进行配置
然而我在测试用注释方式进行配置时,运行后报405错误。
//anno代表URL地址
@WebServlet("/anno")
public class DoFormServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.service(req, resp);
resp.getWriter().println("采用了注释的方法");
}
}
出现原因:
- 继承自HttpServlet的Servlet没有重写对于请求和响应的处理方法:doGet或doPost等方法;默认调用父类的doGet或doPost等方法;
- 父类HttpServlet的doGet或doPost等方法覆盖了你重写的doGet或doPost等方法;
- 不管是1或2,父类HttpServlet的doGet或doPost等方法的默认实现是返回状态代码为405的HTTP错误,表示对于指定资源的请求方法不被允许。
解决方法:
重写doGet,doPost并且不要重写super.doGet和doPost方法,即去掉super(…)