摘要: 原創出處 http://peijie-sh.github.io 歡迎轉載,保留摘要,謝謝!
在使用SpringMVC
時,最重要的2個類就是DispatcherServlet
和ContextLoaderListener
。DispatcherServlet
加載包含Web組件的bean,如控制器、視圖解析器以及處理器映射,ContextLoaderListener
加載應用中的其他bean(通常是驅動應用后端的中間層和數據層組件)。
Servlet 3.0之后
servlet3.0規范出來后,spring3.2有了一種簡便的搭建方式。
直接繼承AbstractAnnotationConfigDispatcherServletInitializer
即可。
這個類會自動創建DispatcherServlet和ContextLoaderListener。這種方式不再需要web.xml,非常方便。
原理:
在Servlet 3.0環境中,容器會在類路徑中查
找實現javax.servlet.ServletContainerInitializer接口的類,如果能發現的話,就會用它來配置Servlet容器。Spring提供了這個接口的實現,名為SpringServletContainerInitializer,這個類反過來又會查找實現WebApplicationInitializer的類并將配置的任務交給它們來完成。
Spring 3.2引入了一個便利的WebApplicationInitializer基礎實現,也就
是AbstractAnnotationConfigDispatcherServletInitializer。
所以我們只要繼承AbstractAnnotationConfigDispatcherServletInitializer(同時也就實現了WebApplicationInitializer),在部署到Servlet 3.0容器中的時候,容器會自動發現它,并用它來配置Servlet上下文。
public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
// 指定配置類
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
// 將DispatcherServlet映射到"/"
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
Servlet 3.0之前
如果你要部署在不支持servlet3.0的容器,比如tomcat6和以下版本,那就只能通過web.xml來配置了。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置根上下文 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 注冊Spring監聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- SpringMVC前端控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation配置springmvc加載的配置文件(配置處理器、映射器、適配器等等)
如果不配置contextConfigLocation,默認加載的是/WEB-INF/servlet名稱- serlvet.xml(springmvc-servlet.xml) -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 指定servlet加載順序,整數越小優先越高 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>