SpringMVC如何与Servlet3整合在一起
1、新建一个AbstractAnnotationConfigDispatcherServletInitializer的实现类,这个类用于在web容器启动的时候创建对象,调用方法来初始化容器以及前段控制器。
package com.gwolf;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MyWebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return null;
}
}

2、新建一个根容器,不需要扫描Controller注解的类。
package com.gwolf;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
@ComponentScan(value="com.gwolf",
excludeFilters= {@Filter(type=FilterType.ANNOTATION,
classes= {Controller.class})})
public class RootConfig {
}

3、protected Class<?>[] getRootConfigClasses() 方法用于获取跟容器的配置类:相当于以前使用配置文件配置的父容器。
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}

4、新建一个子容器,只需要扫描Controller注解的类,在这个配置中useDefaultFilters=false还需要设置此属性禁用默认过滤规则。
package com.gwolf;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.stereotype.Controller;
@ComponentScan(value="com.gwolf",
includeFilters= {@Filter(type=FilterType.ANNOTATION,
classes= {Controller.class})},useDefaultFilters=false)
public class AppConfig {
}

5、@Override
protected Class<?>[] getServletConfigClasses()方式获取web容器的配置类(SpringMVC配置文件)子容器。
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{AppConfig.class};
}

6、protected String[] getServletMappings() 用于获取DispatcherServlet的映射信息,我们现在拦截所有请求,但是不包括*.jsp。
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}

7、建立一个控制类,测试SpringMVC与Servlet3是否整合完成。
package com.gwolf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String hello() {
return "hello";
}
}
启动SpringMVC应用,查看程序是否能够正常执行。
