Servlet3.0整合SpringMvc(注解版)
在创建maven的web工程时候,如果报错缺少web.xml
则在pom添加如下配置 :
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
web容器在启动的时候 会扫描每个jar包下的META-INF/services/javax.servlet.ServletContainerInitializer
加载这个文件指定的启动类
Spring的应用一启动会加载感兴趣的WebApplicationInitializer接口下的所有组件
并且为WebApplicationInitializer 组件创建对象(组件不是接口,不是抽象类)
总结:
以注解方式来启动Spring MVC 继承 AbstractAnnotationConfigDispatcherServletInitializer
实现抽象方法指定 DispatchServlet的配置信息
将Spring mvc 通过注解形式整合
配置:
//web容器启动的时候就会创建对象 调用方法 初始化容器 以及前端控制器 public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { //获取跟容器的配置类 (Spring配置文件) 父容器 @Override protected Class<?>[] getRootConfigClasses() { // TODO Auto-generated method stub return new Class<?>[] {RootConfig.class}; } // 获取web容器的配置类 (Spring mvc配置文件) 创建子容器 @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] {AppConfig.class}; } //获取DispatcherServlet的映射信息 @Override protected String[] getServletMappings() { // /* 拦截所有亲求; 连*.jsp页面都拦截; jsp页面是Tomcat的jsp引擎解析的 return new String[] {"/"}; //拦截所有请求 包括静态资源 } }
AppConfig:
//Spring mvc 只扫描controller 子容器 @ComponentScan(value="com.toov5", includeFilters= { @Filter(type=FilterType.ANNOTATION,classes= {Controller.class})}, useDefaultFilters = false) //禁用默认的过虑规则 public class AppConfig { }
RootConfig:
//Spring的容器不扫描controller 父容器 @ComponentScan(value="com.toov5", excludeFilters= {@Filter(type=FilterType.ANNOTATION,classes= {Controller.class})}) public class RootConfig { }
Controller:
@Controller public class HelloController { @Autowired HelloService HelloService; @ResponseBody @RequestMapping("/hello") public String hello() { String sayHello = HelloService.sayHello("toov5"); return sayHello; } }
Service:
@Service public class HelloService { public String sayHello(String name) { return "Hello:"+name; } }
访问:
在xml配置的spring mvc开发中
<mvc: default-servlet-handler/> 将springmvc处理不了的请求交给tomcat 静态资源就可以访问
<mvc:annotation-driven /> springmvc高级功能开启
<mvc:interceptors> </mvc:interceptors>
<mvc:view-controller path="" />
下面我们定制 Spring mvc
1 @EnableWebMvc 开始Spring mvc 定制配置功能
<mvc:annotation-driven />
2 配置组件(视图解析器 视图映射 静态资源映射 拦截器)
//Spring mvc 只扫描controller 子容器 @SuppressWarnings("deprecation") @ComponentScan(value="com.toov5", includeFilters= { @Filter(type=FilterType.ANNOTATION,classes= {Controller.class})}, useDefaultFilters = false) //禁用默认的过虑规则 @EnableWebMvc public class AppConfig extends WebMvcConfigurerAdapter { //定制视图解析器 @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/views/",".jsp"); } //静态资源访问等等都可配置 }
Controller
@Controller public class HelloController { @Autowired HelloService HelloService; @ResponseBody @RequestMapping("/hello") public String hello() { String sayHello = HelloService.sayHello("toov5"); return sayHello; } @RequestMapping("/su") public String success() { //配置了解析器 return "success"; } }
访问结果:
放入图片,加入jsp:
Jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<img alt="" src="aa.jpg">
</body>
</html>
此时:
没有找到 这个映射 这个请求是被spring mvc处理了 实际上这个是个静态资源 交给tomcat。
下面进行自定义配置 配置静态资源访问
//Spring mvc 只扫描controller 子容器 @SuppressWarnings("deprecation") @ComponentScan(value="com.toov5", includeFilters= { @Filter(type=FilterType.ANNOTATION,classes= {Controller.class})}, useDefaultFilters = false) //禁用默认的过虑规则 @EnableWebMvc public class AppConfig extends WebMvcConfigurerAdapter { //定制视图解析器 @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/views/",".jsp"); } //静态资源访问等等都可配置 @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); //xml:<mvc: default-servlet-handler/> 将springmvc处理不了的请求交给tomcat 静态资源就可以访问 } }
成功!
下面配置一个复杂一点的拦截器:
拦截器:
//需要实现spring mvc 的接口 之前: <mvc:interceptors> </mvc:interceptors> public class MyFirstInterceptor implements HandlerInterceptor{ //目标方法运行之前执行 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("目标方法之前....执行了preHandle"); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("目标方之后....执行了postHandle"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("响应到页面之后....执行了afterCompletion"); } }
配置:
//Spring mvc 只扫描controller 子容器 @SuppressWarnings("deprecation") @ComponentScan(value="com.toov5", includeFilters= { @Filter(type=FilterType.ANNOTATION,classes= {Controller.class})}, useDefaultFilters = false) //禁用默认的过虑规则 @EnableWebMvc public class AppConfig extends WebMvcConfigurerAdapter { //定制视图解析器 @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/views/",".jsp"); } //静态资源访问等等都可配置 @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); //xml:<mvc: default-servlet-handler/> 将springmvc处理不了的请求交给tomcat 静态资源就可以访问 } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyFirstInterceptor()).addPathPatterns("/*"); //添加一个拦截器 也可以从容器中获取 } }
运行: