void_lxy
2017-03-29 12:38:34
Java web HttpServlet中Service和doPost doGet的关系
通过分析Service 源码我们可以发现,HttpServlet中写有Service和doPost/doGet等方法。即我们使用的Servlet继承于Httpservlet,就要重写doPost/doGet。
//请求会先访问这个service
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
if(req instanceof HttpServletRequest && res instanceof HttpServletResponse) {
//将req 和res强制转换为带Http的request 和response
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
//然后调用带Http req和res的service方法
this.service((HttpServletRequest)request, (HttpServletResponse)response);
} else {
throw new ServletException("non-HTTP request or response");
}
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获得请求方法的类型
String method = req.getMethod();
long errMsg;
//如果是GET请求
if(method.equals("GET")) {
errMsg = this.getLastModified(req);
if(errMsg == -1L) {
//调用doGet方法
this.doGet(req, resp);
} else {
long ifModifiedSince = req.getDateHeader("If-Modified-Since");
if(ifModifiedSince < errMsg) {
this.maybeSetLastModified(resp, errMsg);
this.doGet(req, resp);
} else {
resp.setStatus(304);
}
}
//如果是HEAD请求
} else if(method.equals("HEAD")) {
errMsg = this.getLastModified(req);
this.maybeSetLastModified(resp, errMsg);
this.doHead(req, resp);
//如果是POST请求
} else if(method.equals("POST")) {
this.doPost(req, resp);
//如果是PUT请求
} else if(method.equals("PUT")) {
this.doPut(req, resp);
//如果是DELETE请求
} else if(method.equals("DELETE")) {
this.doDelete(req, resp);
//如果是OPTIONS请求
} else if(method.equals("OPTIONS")) {
this.doOptions(req, resp);
} else if(method.equals("TRACE")) {
this.doTrace(req, resp);
} else {
String errMsg1 = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[]{method};
errMsg1 = MessageFormat.format(errMsg1, errArgs);
resp.sendError(501, errMsg1);
}
}
我们可以将自己对Http传递数据的处理写在重写后的doPost或者doGet方法当中,但是如果我们要重写Service方法,那么父类的Service方法会被覆盖。则重写后的doPost和doGet方法将不会生效,故我们需要加上
super.Service(request,response);
这样当前servlet下的doPost和doGet方法才会生效。
评论
最近浏览
ZGNDream LV12
2020年10月9日


