Spring中
配置interceptors
<mvc:view-controller path="/hello" view-name="success"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
<mvc:default-servlet-handler/>
Spring boot实现方式
参考官网
https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications
可以扩展Spring MVC功能
编写一个配置类@Configuration
是WebMvcConfigurerAdapter类型,不能标注@EnableWebMvc
既保留了所有的自动配置,也能用自定义扩展的配置
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
//@EnableWebMvc 不要接管SpringMVC
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送 /atguigu 请求来到 success
registry.addViewController("/atguigu").setViewName("success");
}
}
实现原理
WebMvcAutoConfiguration
SpringMVC的自动配置类
搜索,WebMvcAutoConfigurationAdapter
EnableWebMvcConfiguration
在做其他自动配置时会导入
@Import(EnableWebMvcConfiguration.class)
DelegatingWebMvcConfiguration
搜索,setConfigurers
从容器中获取,所有的WebMvcConfigurer
addViewControllers
从容器中获取,所有的WebMvcConfigurer
把它们的addViewControllers方法,都调用一遍
addViewControllers
将所有的WebMvcConfigurer相关配置,都一起来调用
就都会一起,来起作用
容器中
所有的WebMvcConfigurer都会一起起作用
自定义的配置类,也会被调用
自动配置类,其作用的时候,会扫描容器中
所有的配置类,自定义的配置类,也会扫描到
SpringMVC的自动配置,和自定义的扩展配置都会起作用