用SpringMVC搭建web应用

SpringMVC

在使用SpringMVC时,最重要的2个类就是DispatcherServletContextLoaderListenerDispatcherServlet加载包含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上下文。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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来配置了。

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
<?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>