3.1、DispatcherServlet作用
DispatcherServlet是前端控制器設計模式的實作,提供Spring Web MVC的集中通路點,而且負責職責的分派,而且與Spring IoC容器無縫內建,進而可以獲得Spring的所有好處。 具體請參考第二章的圖2-1。
DispatcherServlet主要用作職責排程工作,本身主要用于控制流程,主要職責如下:
1、檔案上傳解析,如果請求類型是multipart将通過MultipartResolver進行檔案上傳解析;
2、通過HandlerMapping,将請求映射到處理器(傳回一個HandlerExecutionChain,它包括一個處理器、多個HandlerInterceptor攔截器);
3、通過HandlerAdapter支援多種類型的處理器(HandlerExecutionChain中的處理器);
4、通過ViewResolver解析邏輯視圖名到具體視圖實作;
5、本地化解析;
6、渲染具體的視圖等;
7、如果執行過程中遇到異常将交給HandlerExceptionResolver來解析。
從以上我們可以看出DispatcherServlet主要負責流程的控制(而且在流程中的每個關鍵點都是很容易擴充的)。
3.2、DispatcherServlet在web.xml中的配置
1 2 3 4 5 6 7 8 9 <
servlet
>
<
servlet-name
>chapter2</
servlet-name
>
<
servlet-class
>org.springframework.web.servlet.DispatcherServlet</
servlet-class
>
<
load-on-startup
>1</
load-on-startup
>
</
servlet
>
<
servlet-mapping
>
<
servlet-name
>chapter2</
servlet-name
>
<
url-pattern
>/</
url-pattern
>
</
servlet-mapping
>
load-on-startup:表示啟動容器時初始化該Servlet;
url-pattern:表示哪些請求交給Spring Web MVC處理, “/” 是用來定義預設servlet映射的。也可以如“*.html”表示攔截所有以html為擴充名的請求。
該DispatcherServlet預設使用WebApplicationContext作為上下文,Spring預設配置檔案為“/WEB-INF/[servlet名字]-servlet.xml”。
DispatcherServlet也可以配置自己的初始化參數,覆寫預設配置:
摘自Spring Reference
參數 描述 contextClass 實作WebApplicationContext接口的類,目前的servlet用它來建立上下文。如果這個參數沒有指定, 預設使用XmlWebApplicationContext。 contextConfigLocation 傳給上下文執行個體(由contextClass指定)的字元串,用來指定上下文的位置。這個字元串可以被分成多個字元串(使用逗号作為分隔符) 來支援多個上下文(在多上下文的情況下,如果同一個bean被定義兩次,後面一個優先)。 namespace WebApplicationContext命名空間。預設值是[server-name]-servlet。
是以我們可以通過添加初始化參數
1 2 3 4 5 6 7 8 9 <
servlet
>
<
servlet-name
>chapter2</
servlet-name
>
<
servlet-class
>org.springframework.web.servlet.DispatcherServlet</
servlet-class
>
<
load-on-startup
>1</
load-on-startup
>
<
init-param
>
<
param-name
>contextConfigLocation</
param-name
>
<
param-value
>classpath:spring-servlet-config.xml</
param-value
>
</
init-param
>
</
servlet
>
如果使用如上配置,Spring Web MVC架構将加載“classpath:spring-servlet-config.xml”來進行初始化上下文而不是“/WEB-INF/[servlet名字]-servlet.xml”。
3.3、上下文關系
內建Web環境的通用配置:
1 2 3 4 5 6 7 8 9 <
context-param
>
<
param-name
>contextConfigLocation</
param-name
>
<
param-value
>
classpath:spring-common-config.xml,
classpath:spring-budget-config.xml
</
param-value
>
</
context-param
>
<
listener
> <
listener-class
>org.springframework.web.context.ContextLoaderListener</
listener-class
>
</
listener
>
如上配置是Spring內建Web環境的通用配置;一般用于加載除Web層的Bean(如DAO、Service等),以便于與其他任何Web架構內建。
contextConfigLocation:表示用于加載Bean的配置檔案;
contextClass:表示用于加載Bean的ApplicationContext實作類,預設WebApplicationContext。
建立完畢後會将該上下文放在ServletContext:
1 2 3 servletContext.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
this
.context);
ContextLoaderListener初始化的上下文和DispatcherServlet初始化的上下文關系,如圖3-1
spring mvc 第三章 圖3-1
從圖中可以看出:
ContextLoaderListener初始化的上下文加載的Bean是對于整個應用程式共享的,不管是使用什麼表現層技術,一般如DAO層、Service層Bean;
DispatcherServlet初始化的上下文加載的Bean是隻對Spring Web MVC有效的Bean,如Controller、HandlerMapping、HandlerAdapter等等,該初始化上下文應該隻加載Web相關元件。
3.4、DispatcherServlet初始化順序
繼承體系結構如下所示:
spring mvc 第三章 1、HttpServletBean繼承HttpServlet,是以在Web容器啟動時将調用它的init方法,該初始化方法的主要作用
:::将Servlet初始化參數(init-param)設定到該元件上(如contextAttribute、contextClass、namespace、contextConfigLocation),通過BeanWrapper簡化設值過程,友善後續使用;
:::提供給子類初始化擴充點,initServletBean(),該方法由FrameworkServlet覆寫。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public
abstract
class
HttpServletBean
extends
HttpServlet
implements
EnvironmentAware{
@Override
public
final
void
init()
throws
ServletException {
//省略部分代碼
//1、如下代碼的作用是将Servlet初始化參數設定到該元件上
//如contextAttribute、contextClass、namespace、contextConfigLocation;
try
{
PropertyValues pvs =
new
ServletConfigPropertyValues(getServletConfig(),
this
.requiredProperties);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(
this
);
ResourceLoader resourceLoader =
new
ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.
class
,
new
ResourceEditor(resourceLoader,
this
.environment));
initBeanWrapper(bw);
bw.setPropertyValues(pvs,
true
);
}
catch
(BeansException ex) {
//…………省略其他代碼
}
//2、提供給子類初始化的擴充點,該方法由FrameworkServlet覆寫
initServletBean();
if
(logger.isDebugEnabled()) {
logger.debug(
"Servlet '"
+ getServletName() +
"' configured successfully"
);
}
}
//…………省略其他代碼
}
2、FrameworkServlet繼承HttpServletBean,通過initServletBean()進行Web上下文初始化,該方法主要覆寫一下兩件事情:
初始化web上下文;
提供給子類初始化擴充點;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 public
abstract
class
FrameworkServlet
extends
HttpServletBean {
@Override
protected
final
void
initServletBean()
throws
ServletException {
//省略部分代碼
try
{
//1、初始化Web上下文
this
.webApplicationContext = initWebApplicationContext();
//2、提供給子類初始化的擴充點
initFrameworkServlet();
}
//省略部分代碼
}
}
protected
WebApplicationContext initWebApplicationContext() {
//ROOT上下文(ContextLoaderListener加載的)
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac =
null
;
if
(
this
.webApplicationContext !=
null
) {
// 1、在建立該Servlet注入的上下文
wac =
this
.webApplicationContext;
if
(wac
instanceof
ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if
(!cwac.isActive()) {
if
(cwac.getParent() ==
null
) {
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if
(wac ==
null
) {
//2、查找已經綁定的上下文
wac = findWebApplicationContext();
}
if
(wac ==
null
) {
//3、如果沒有找到相應的上下文,并指定父親為ContextLoaderListener
wac = createWebApplicationContext(rootContext);
}
if
(!
this
.refreshEventReceived) {
//4、重新整理上下文(執行一些初始化)
onRefresh(wac);
}
if
(
this
.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
//省略部分代碼
}
return
wac;
}
從initWebApplicationContext()方法可以看出,基本上如果ContextLoaderListener加載了上下文将作為根上下文(DispatcherServlet的父容器)。
最後調用了onRefresh()方法執行容器的一些初始化,這個方法由子類實作,來進行擴充。
3、DispatcherServlet繼承FrameworkServlet,并實作了onRefresh()方法提供一些前端控制器相關的配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public
class
DispatcherServlet
extends
FrameworkServlet {
//實作子類的onRefresh()方法,該方法委托為initStrategies()方法。
@Override
protected
void
onRefresh(ApplicationContext context) {
initStrategies(context);
}
//初始化預設的Spring Web MVC架構使用的政策(如HandlerMapping)
protected
void
initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
}
從如上代碼可以看出,DispatcherServlet啟動時會進行我們需要的Web層Bean的配置,如HandlerMapping、HandlerAdapter等,而且如果我們沒有配置,還會給我們提供預設的配置。
從如上代碼我們可以看出,整個DispatcherServlet初始化的過程和做了些什麼事情,具體主要做了如下兩件事情:
1、初始化Spring Web MVC使用的Web上下文,并且可能指定父容器為(ContextLoaderListener加載了根上下文);
2、初始化DispatcherServlet使用的政策,如HandlerMapping、HandlerAdapter等。
伺服器啟動時的日志分析(此處加上了ContextLoaderListener進而啟動ROOT上下文容器):
資訊: Initializing Spring root WebApplicationContext //由ContextLoaderListener啟動ROOT上下文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 2012-03-12 13:33:55 [main] INFO <strong>org.springframework.web.context.ContextLoader</strong> - Root WebApplicationContext: initialization started
2012-03-12 13:33:55 [main] INFO org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Mon Mar 12 13:33:55 CST 2012]; root of context hierarchy
2012-03-12 13:33:55 [main] DEBUG org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader - Loading bean definitions
2012-03-12 13:33:55 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 0 bean definitions from location pattern <strong>[/WEB-INF/ContextLoaderListener.xml]</strong><strong></strong>
2012-03-12 13:33:55 [main] DEBUG org.springframework.web.context.support.XmlWebApplicationContext - Bean factory for Root WebApplicationContext: org.s[email protected]1c05ffd: defining beans []; root of factory hierarchy
2012-03-12 13:33:55 [main] DEBUG org.springframework.web.context.support.XmlWebApplicationContext - Bean factory for Root WebApplicationContext:
<strong>2012-03-12 13:33:55 [main] DEBUG org.springframework.web.context.ContextLoader - Published root WebApplicationContext as ServletContext attribute with name [org.springframework.web.context.WebApplicationContext.ROOT] </strong><strong>//</strong><strong>将</strong><strong>ROOT</strong><strong>上下文綁定到</strong><strong>ServletContext</strong><strong></strong>
2012-03-12 13:33:55 [main] INFO org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 438 ms<strong> //</strong><strong>到此</strong><strong>ROOT</strong><strong>上下文啟動完畢</strong>
2012-03-12 13:33:55 [main] DEBUG org.springframework.web.servlet.DispatcherServlet - Initializing servlet 'chapter2'
資訊: Initializing Spring FrameworkServlet 'chapter2' <strong>//</strong><strong>開始初始化</strong><strong>FrameworkServlet</strong><strong>對應的</strong><strong>Web</strong><strong>上下文</strong><strong></strong>
2012-03-12 13:33:55 [main] INFO org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'chapter2': initialization started
2012-03-12 13:33:55 [main] DEBUG org.springframework.web.servlet.DispatcherServlet - Servlet with name 'chapter2' will try to<strong> create custom WebApplicationContext context</strong> of class 'org.springframework.web.context.support.XmlWebApplicationContext', <strong>using parent context [Root WebApplicationContext</strong>: startup date [Mon Mar 12 13:33:55 CST 2012]; root of context hierarchy]
<strong>//</strong><strong>此處使用</strong><strong>Root WebApplicationContext</strong><strong>作為父容器。</strong><strong></strong>
2012-03-12 13:33:55 [main] INFO org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'chapter2-servlet': startup date [Mon Mar 12 13:33:55 CST 2012]; parent: Root WebApplicationContext
2012-03-12 13:33:55 [main] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [<strong>/WEB-INF/chapter2-servlet.xml]</strong>
2012-03-12 13:33:55 [main] DEBUG org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader - Loading bean definitions
2012-03-12 13:33:55 [main] DEBUG org.springframework.beans.factory.xml.BeanDefinitionParserDelegate - Neither XML 'id' nor 'name' specified - using generated bean name<strong>[org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping#0]</strong><strong> //</strong><strong>我們配置的</strong><strong>HandlerMapping</strong>
2012-03-12 13:33:55 [main] DEBUG org.springframework.beans.factory.xml.BeanDefinitionParserDelegate - Neither XML 'id' nor 'name' specified - using generated bean name<strong>[org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter#0] </strong><strong>//</strong><strong>我們配置的</strong><strong>HandlerAdapter</strong>
2012-03-12 13:33:55 [main] DEBUG org.springframework.beans.factory.xml.BeanDefinitionParserDelegate - Neither XML 'id' nor 'name' specified - using generated bean name [org.springframework.web.servlet.view.InternalResourceViewResolver#0] <strong>//</strong><strong>我們配置的</strong><strong>ViewResolver</strong>
2012-03-12 13:33:55 [main] DEBUG org.springframework.beans.factory.xml.BeanDefinitionParserDelegate - No XML 'id' specified - using '/hello' as bean name and [] as aliases
<strong>//</strong><strong>我們的處理器(</strong><strong>HelloWorldController</strong><strong>)</strong><strong></strong>
2012-03-12 13:33:55 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 4 bean definitions from location pattern [/WEB-INF/chapter2-servlet.xml]
2012-03-12 13:33:55 [main] DEBUG org.springframework.web.context.support.XmlWebApplicationContext - Bean factory for WebApplicationContext for namespace 'chapter2-servlet': org.s[email protected]1372656: defining beans [org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping#0,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter#0,org.springframework.web.servlet.view.InternalResourceViewResolver#0,/hello]; parent: org.s[email protected]1c05ffd
<strong>//</strong><strong>到此容器注冊的Bean</strong><strong>初始化完畢</strong>
2012-03-12 13:33:56 [main] DEBUG org.springframework.web.servlet.DispatcherServlet - Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided
2012-03-12 13:33:56 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver'
<strong>//</strong><strong>預設的</strong><strong>LocaleResolver</strong><strong>注冊</strong><strong></strong>
2012-03-12 13:33:56 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.theme.FixedThemeResolver'
<strong>//</strong><strong>預設的</strong><strong>ThemeResolver</strong><strong>注冊</strong><strong></strong>
2012-03-12 13:33:56 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping#0'
<strong>//</strong><strong>發現我們定義的</strong><strong>HandlerMapping </strong><strong>不再</strong><strong>使用預設的</strong><strong>HandlerMapping</strong><strong>。</strong><strong></strong>
2012-03-12 13:33:56 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter#0'
<strong>//</strong><strong>發現我們定義的</strong><strong>HandlerAdapter </strong><strong>不再</strong><strong>使用預設的</strong><strong>HandlerAdapter</strong><strong>。</strong><strong></strong>
2012-03-12 13:33:56 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver'
<strong>//</strong><strong>異常處了解析器</strong><strong>ExceptionResolver</strong>
2012-03-12 13:33:56 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver'
2012-03-12 13:33:56 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.web.servlet.view.InternalResourceViewResolver#0'
2012-03-12 13:33:56 [main] DEBUG org.springframework.web.servlet.DispatcherServlet - Published WebApplicationContext of servlet 'chapter2' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.chapter2]
<strong>//</strong><strong>綁定</strong><strong>FrameworkServlet</strong><strong>初始化的</strong><strong>Web</strong><strong>上下文到</strong><strong>ServletContext</strong>
2012-03-12 13:33:56 [main] INFO org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'chapter2': initialization completed in 297 ms
2012-03-12 13:33:56 [main] DEBUG org.springframework.web.servlet.DispatcherServlet - Servlet 'chapter2' configured successfully
<strong>//</strong><strong>到此完整流程結束</strong>
從如上日志我們也可以看出,DispatcherServlet會進行一些預設的配置。接下來我們看一下預設配置吧。
3.5、DispatcherServlet預設配置
DispatcherServlet的預設配置在DispatcherServlet.properties(和DispatcherServlet類在一個包下)中,而且是當Spring配置檔案中沒有指定配置時使用的預設政策:
spring mvc 第三章 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver
org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver
org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\
org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\
org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator
org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver
org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager
從如上配置可以看出DispatcherServlet在啟動時會自動注冊這些特殊的Bean,無需我們注冊,如果我們注冊了,預設的将不會注冊。
是以如第二章的BeanNameUrlHandlerMapping、SimpleControllerHandlerAdapter是不需要注冊的,DispatcherServlet預設會注冊這兩個Bean。
從DispatcherServlet.properties可以看出有許多特殊的Bean,那接下來我們就看看Spring Web MVC主要有哪些特殊的Bean。
3.6、DispatcherServlet中使用的特殊的Bean
DispatcherServlet預設使用WebApplicationContext作為上下文,是以我們來看一下該上下文中有哪些特殊的Bean:
1、Controller:處理器/頁面控制器,做的是MVC中的C的事情,但控制邏輯轉移到前端控制器了,用于對請求進行處理;
2、HandlerMapping:請 求到處理器的映射,如果映射成功傳回一個HandlerExecutionChain對象(包含一個Handler處理器(頁面控制器)對象、多個 HandlerInterceptor攔截器)對象;如BeanNameUrlHandlerMapping将URL與Bean名字映射,映射成功的 Bean就是此處的處理器;
3、HandlerAdapter:HandlerAdapter 将會把處理器包裝為擴充卡,進而支援多種類型的處理器,即擴充卡設計模式的應用,進而很容易支援很多類型的處理器;如 SimpleControllerHandlerAdapter将對實作了Controller接口的Bean進行适配,并且掉處理器的 handleRequest方法進行功能處理;
4、ViewResolver:ViewResolver将把邏輯視圖名解析為具體的View,通過這種政策模式,很容易更換其他視圖技術;如InternalResourceViewResolver将邏輯視圖名映射為jsp視圖;
5、LocalResover:本地化解析,因為Spring支援國際化,是以LocalResover解析用戶端的Locale資訊進而友善進行國際化;
6、ThemeResovler:主題解析,通過它來實作一個頁面多套風格,即常見的類似于軟體皮膚效果;
7、MultipartResolver:檔案上傳解析,用于支援檔案上傳;
8、HandlerExceptionResolver:處理器異常解析,可以将異常映射到相應的統一錯誤界面,進而顯示使用者友好的界面(而不是給使用者看到具體的錯誤資訊);
9、RequestToViewNameTranslator:當處理器沒有傳回邏輯視圖名等相關資訊時,自動将請求URL映射為邏輯視圖名;
10、FlashMapManager:用于管理FlashMap的政策接口,FlashMap用于存儲一個請求的輸出,當進入另一個請求時作為該請求的輸入,通常用于重定向場景,後邊會細述。
到此DispatcherServlet我們已經了解了,接下來我們就需要把上邊提到的特殊Bean挨個擊破,那首先從控制器開始吧