更详细的信息可以观看 : http://blog.csdn.net/gebitan505/article/details/70142025
非springBoot下
一般非springBoot下的拦截器都是实现HandlerInterceptor接口为主,或者实现拦截器适配器来处理自定义拦截器的,
一般处理于:(1);拦截前处理(2)请求处理(3)请求处理完后的处理
实际而言,我们是处理实现拦截器适配器,利用是配偶器模式来进行对所需处理方式选择。 在web.xml中配置拦截器即可。
springBoot模式:
(1)方式一
由于没有web.xml这个配置文件,所以我们需要继承WebMvcConfigurerAdapter,来替代web..xml配置文件,并在类上加上注解@Configuration
重写addInterceptors方法,加入自定义拦截器,就可以执行自己的代码。
@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter{
/**
* 注册 拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptorAdapter() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("222222222222 WebMvcConfigurer.interceptor====");
return true;
}
}).addPathPatterns("/*");
}
}
同时可以在后方加入拦截路径,用于拦截请求。放行路径在之后加上.excludePathPatterns(这里填写要放行的路径),可以连续加上 数条
(2)方式二
springBoot启动器上加注释
@ImportResource("classpath:/springMVC.xml")
读取配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<!-- 配置组件扫描 -->
<!-- 配置mvc注解驱动 -->
<mvc:annotation-driven />
<!-- 配置视图解析器 -->
<!-- 静态资源,用WEB容器中默认的Servlet来处理 -->
<mvc:default-servlet-handler />
<!-- 配置拦截器 -->
<mvc:interceptors>
<!-- 配置登录拦截器 -->
<mvc:interceptor>
<!-- 配置拦截的URL -->
<mvc:mapping path="/**" />
<!-- 配置登录拦截器Bean -->
<bean class="com.pp.interceptor.LogHandlerInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
</beans>
方式2的放行路径:
<mvc:exclude-mapping path="/login"/>
静态资源处理
对于只能通过内部访问的资源,在非springBoot情况下是 webapp/WEB-INF下的资源外部无法直接访问
springBoot则是/src/main/resources/META-INF/resources/WEB-INF
记得resources是自定义的文件下,是初始化配置的时候可以读取
在spring-boot-autoconfigure-1.5.6.RELEASE.jar的web包的ResourceProperties类中作了默认的配置: