可以很清楚的看到, 在tomcat的實現中, service方法只起到了類似調度的功能
所以我們平時只重寫doGet或doPost方法后, 會自動按請求類型匹配執行
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
...
doGet(req, resp);
...
} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
} else if (method.equals(METHOD_POST)) {
doPost(req, resp);
} else if (method.equals(METHOD_PUT)) {
doPut(req, resp);
} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp);
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp);
} else if (method.equals(METHOD_TRACE)) {
doTrace(req,resp);
} else {
...
}
}
可見tomcat實現的service方法只是起到了調度請求的作用
如果我們重寫了service方法, 父類HttpServlet中的service方法就會失效
所以收到的任何請求都會由我們自己覆寫的service方法來處理
如果我們的servlet中只有service方法, 是沒有問題的
但值得注意的是, 如果你同時重寫了service和doGet, doPost方法
一定要在執行完自己代碼后調用父類service方法, super.service;
否自你的doGet和doPost是不會被執行的
doPost方法里面調用doGet方法做下面解釋:---------------------|
doget和dopost方法的意思,為什么在servlet中dopost中調用doget方法 原創 2017年08月06日 20:17:39 doget調用dopost或者dopost調用doget一般是在教科書或者不需要區分get還是post方法調用的場合下使用。 沒有默認調用哪個的說法,http訪問請求的兩種方式get和post,你使用那種方式請求,servlet就會用對應的方法來處理你的請求。 你用get方式請求,那么servlet就會執行doget方法,反之,你用post方式請求,servlet就會執行都post方法。
