一、HTTP Servlet
Javax.servlet.http包时Servlet API中的第二个包,包含编写Servlet应用程序的类和接口,其中的许多类型都覆盖了javax.servlet中的类型。下图展示了javax.servlet.http中的主要类型。
二、HttpServlet
HttpServlet类覆盖javax.servletGenericServlet类。在使用HttpServlet时,HttpServletRequest与HttpServletResponse分别表示Servlet请求和Servlet响应。其中,HttpServletRequest接口继承了ServletRequest,HttpServletResponse接口继承了ServletResponse。
public interface HttpServletRequest extends ServletRequest
public interface HttpServletResponse extends ServletResponse
HrtpServlet覆盖GenericServlet中的service方法。这个新的service方法与Servlet中的区别在于,前者接收的是HttpServletRequest对象和HttpServletResposne对象。
原始的service方法将请求和响应对象进行向下转换,分别从Servlet容器转换成HttpServletRequest和HttpServletResposne,并调用新的service方法。
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {HttpServletRequest request;HttpServletResponse response;try {request = (HttpServletRequest)req;response = (HttpServletResponse)res;} catch (ClassCastException var6) {throw new ServletException("non-HTTP request or response");}this.service(request, response);
}
HrtpServlet中新的service方法通过查看发送的HTTP请求方式(通过调用request.getMethod),再调用以下某个方法(doGet、doPoSt、doHead、doPut、doTrace、doOptions和doDelete)。其中doGet和doPost是最常用的。隐藏,不需要再覆盖service方法,直接覆盖doGet或者doPost。
下面就是这个过程的实现代码
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String method = req.getMethod();long lastModified;
if (method.equals("GET")) { //Get请求方式lastModified = this.getLastModified(req);if (lastModified == -1L) {this.doGet(req, resp);} else {long ifModifiedSince = req.getDateHeader("If-Modified-Since");if (ifModifiedSince < lastModified) {this.maybeSetLastModified(resp, lastModified);this.doGet(req, resp);} else {resp.setStatus(304);}}} else if (method.equals("HEAD")) {lastModified = this.getLastModified(req);this.maybeSetLastModified(resp, lastModified);this.doHead(req, resp);} else if (method.equals("POST")) { //Post请求方式this.doPost(req, resp);} else if (method.equals("PUT")) {this.doPut(req, resp);} else if (method.equals("DELETE")) {this.doDelete(req, resp);} else if (method.equals("OPTIONS")) {this.doOptions(req, resp);} else if (method.equals("TRACE")) {this.doTrace(req, resp);} else {String errMsg = lStrings.getString("http.method_not_implemented");Object[] errArgs = new Object[]{method};errMsg = MessageFormat.format(errMsg, errArgs);resp.sendError(501, errMsg);}}