1. Servlet处理各种请求
- service:处理所有请求
- doGet:处理GET请求
- doPost:处理POST请求
- doPut:处理PUT请求
- doDelete:处理DELETE请求
- doHead:处理HEAD请求
- doOptions:处理OPTIONS请求
1 | public class MyServlet extends HttpServlet { |
如果你重写了service,又重写了doXxx,那么只有service会被调用1
2
3
4
5
6
7
8
9
10/** 只调用service */
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("service");
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet");
}
但是如果你在service中调用父类的service,则会发现,doXxx也会被调用。这说明,父类的service会根据请求的类型,调用对应的doXxx1
2
3
4
5
6
7
8
9
10
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("service");
super.service(req, resp);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet");
}
2. 405错误:请求方式不支持
如果调用了父类的service,你又没有重写相应的doXxx,则发起请求时,就返回HTTP Status 405 – Method Not Allowed,表示服务器无法处理该请求1
2
3
4
5
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("service");
super.service(req, resp);
}