HttpServlet#service
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取请求类型 String method = req.getMethod(); //如果是get请求 if (method.equals(METHOD_GET)) { //检查是不是开启了页面缓存 通过header头的 Last-Modified/If-Modified-Since //获取Last-Modified的值 long lastModified = getLastModified(req); if (lastModified == -1) { // servlet doesn't support if-modified-since, no reason // to go through further expensive logic //没有开启页面缓存调用doGet方法 doGet(req, resp); } else { long ifModifiedSince; try { //获取If-Modified-Since的值 ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE); } catch (IllegalArgumentException iae) { ifModifiedSince = -1; } if (ifModifiedSince < (lastModified / 1000 * 1000)) { // If the servlet mod time is later, call doGet() // Round down to the nearest second for a proper compare // A ifModifiedSince of -1 will always be less //更新Last-Modified maybeSetLastModified(resp, lastModified); //调用doGet方法 doGet(req, resp); } else { //设置304状态码 在HttpServletResponse中定义了很多常用的状态码 resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } } else if (method.equals(METHOD_HEAD)) { //调用doHead方法 long lastModified = getLastModified(req); maybeSetLastModified(resp, lastModified); doHead(req, resp); } else if (method.equals(METHOD_POST)) { //调用doPost方法 doPost(req, resp); } else if (method.equals(METHOD_PUT)) { //调用doPost方法 doPut(req, resp); } else if (method.equals(METHOD_DELETE)) { //调用doPost方法 doDelete(req, resp); } else if (method.equals(METHOD_OPTIONS)) { //调用doPost方法 doOptions(req,resp); } else if (method.equals(METHOD_TRACE)) { //调用doPost方法 doTrace(req,resp); } else { //服务器不支持的方法 直接返回错误信息 String errMsg = lStrings.getString("http.method_not_implemented"); Object[] errArgs = new Object[1]; errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); } }
根据请求类型调用响应的请求方法如果GET类型,调用doGet方法
POST类型,调用doPost方法。
这些方法都是在HttpServlet中定义的,平时我们做web开发的时候主要是继承HttpServlet这个类,然后重写它的doPost或者doGet方法。
我们的FrameworkServlet这个子类就重写了这些方法中的一部分:doGet、doPost、doPut、doDelete、doOption、doTrace。
这里我们只说我们最常用的doGet和doPost这两个方法。通过翻开源码我们发现,这两个方法体的内容是一样的,都是调用了processRequest
FrameworkServlet#processRequest
protected final void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); Throwable failureCause = null; LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext(); //国际化 LocaleContext localeContext = buildLocaleContext(request); RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes(); //构建ServletRequestAttributes对象 ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes); //异步管理 WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor()); //初始化ContextHolders initContextHolders(request, localeContext, requestAttributes); //执行doService try { doService(request, response); } finally { //重新设置ContextHolders resetContextHolders(request, previousLocaleContext, previousAttributes); if (requestAttributes != null) { requestAttributes.requestCompleted(); } //发布请求处理事件 publishRequestHandledEvent(request, response, startTime, failureCause); } }
国际化的设置,创建ServletRequestAttributes对象,初始化上下文holders(即将Request对象放入到线程上下文中),调用doService方法。
国际化的设置
DispatcherServlet#buildLocaleContext这个方法中完成的,其源码如下:
protected LocaleContext buildLocaleContext(final HttpServletRequest request) { if (this.localeResolver instanceof LocaleContextResolver) { return ((LocaleContextResolver) this.localeResolver).resolveLocaleContext(request); } else { return new LocaleContext() { @Override public Locale getLocale() { return localeResolver.resolveLocale(request); } }; } }
没有配置国际化解析器的话,那么它会使用默认的解析器:AcceptHeaderLocaleResolver,即从Header中获取国际化的信息。
除了AcceptHeaderLocaleResolver之外,SpringMVC中还提供了这样的几种解析器:CookieLocaleResolver、SessionLocaleResolver、FixedLocaleResolver。分别从cookie、session中去国际化信息和JVM默认的国际化信息(Local.getDefault())。
initContextHolders这个方法主要是将Request请求、ServletRequestAttribute对象和国际化对象放入到上下文中。其源码如下:
private void initContextHolders( HttpServletRequest request, LocaleContext localeContext, RequestAttributes requestAttributes) { if (localeContext != null) { LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);//threadContextInheritable默认为false } if (requestAttributes != null) {//threadContextInheritable默认为false RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable); } }
RequestContextHolder这个类有什么用呢?有时候我们想在某些类中获取HttpServletRequest对象,比如在AOP拦截的类中,那么我们就可以这样来获取Request的对象了,
HttpServletRequest request = (HttpServletRequest) RequestContextHolder.getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_REQUEST);
DispatcherServlet#doService
@Override protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> attributesSnapshot = null; if (WebUtils.isIncludeRequest(request)) { attributesSnapshot = new HashMap<String, Object>(); Enumeration<?> attrNames = request.getAttributeNames(); while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); if (this.cleanupAfterInclude || attrName.startsWith("org.springframework.web.servlet")) { attributesSnapshot.put(attrName, request.getAttribute(attrName)); } } } //Spring上下文 request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext()); //国际化解析器 request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver); //主题解析器 request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver); //主题 request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource()); //重定向的数据 FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response); if (inputFlashMap != null) { request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap)); } request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap()); request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager); try { //调用doDispatch方法-核心方法 doDispatch(request, response); } finally { if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) { // Restore the original attribute snapshot, in case of an include. if (attributesSnapshot != null) { restoreAttributesAfterInclude(request, attributesSnapshot); } } } }
处理include标签的请求,将上下文放到request的属性中,将国际化解析器放到request的属性中,将主题解析器放到request属性中,将主题放到request的属性中,处理重定向的请求数据最后调用doDispatch这个核心的方法对请求进行处理