-
平常使用servlet的时候,一般会创建一个servlet类去继承HttpServlet这个抽象类,然后根据需要,重写实现doGet方法或者doPost方法,让tomcat来调度浏览器发出的对动态资源文件(class字节码文件)的请求。那这些方法底层到底做了什么呢?
1. 首先我们要知道所有继承了HttpServlet的类,tomcat才有资格去调用它们。
2. 假如现在有个类叫MyServlet
,那么tomcat会在浏览器发出请求后,执行Servlet myServlet = new MyServlet();
然后再用这个Servlet对象去调用service()方法,myServlet.service();
这个时候我们就需要看一下源码,彻底搞明白service是做什么的。
service()源码:
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
long lastModified;
if (method.equals("GET")) {
lastModified = this.getLastModified(req);
if (lastModified == -1L) {
this.doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader("If-Modified-Since");
} catch (IllegalArgumentException var9) {
ifModifiedSince = -1L;
}
if (ifModifiedSince < lastModified / 1000L * 1000L) {
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")) {
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);
}
}
3. 从源码中不难看出,当tomcat调用了service方法后,方法中会先获取浏览器发送来的请求是什么方式的。
如果这个method
是get方式那就调用doGet方法。(this.doGet(req,resp);//这里的this就是我们创建的MyServlet
)
如果这个method
是post方式那就调用doPost方法。
4. http协议常见的七种请求都在service方法里面,大多数只会发送POST和GET请求。
(1) GET
- 向特定的资源发出请求。
(2) POST
- 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。
(3) HEAD
- 向服务器索取与GET请求相一致的响应,只不过响应体将不会被返回。
(4) OPTIONS
- 返回服务器针对特定资源所支持的HTTP请求方法。
(5) PUT
- 向指定资源位置上传其最新内容
(6) DELETE
- 请求服务器删除Request-URL所标识的资源
(7)TRACE
- 回显服务器收到的请求,主要用于测试或诊断。
注意:
浏览器以GET方式发送请求时,请求参数放在请求头里,在http请求协议包到达http服务器后,会先解码,请求头的二进制内容由tomcat解码,tomcat默认用utf-8。
浏览器以POST方式发送请求时,请求参数保存在请求体中,在http请求协议包到达http服务器后,也是先解码,请求体中的二进制数据由请求对象(request)负责解码,request默认使用ISO-8859-1。
如果需要设置为utf-8,需要以下代码:
request.setCharacterEncoding("utf-8");