拦截器可以完成权限校验,身份验证,记录操作日志等常见功能
在Spring Boot1.x中,使用拦截器时需要在继承了WebMvcConfigurerAdapter类的@Configuration类中进行注册,但是在Spring Boot2.x中,WebMvcConfigurerAdapter类被deprecated了因此最好不要使用这种方式
WebMvcConfigurerAdapter源码
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer
虽然不能使用WebMvcConfigurerAdapter类,但我们可以继续使用WebMvcConfigurer接口,所以我们通过实现了WebMvcConfigurer接口的@Configuration类完成拦截器的注册
1.编写自定义拦截器
新建com.neuedu.interceptor包,在包中新建类MyInterceptor并实现org.springframework.web.servlet.HandlerInterceptor接口
package com.neuedu.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class MyInterceptor implements HandlerInterceptor{
/**
* 前置处理:进入处理器方法前触发
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("前置处理");
return HandlerInterceptor.super.preHandle(request, response, handler);
}
/**
* 后置处理:执行处理器方法后触发
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("后置处理");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
/**
* 最终处理:视图渲染后触发
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("最终处理");
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
2.编写@Configuration类完成注册
在com.neuedu包中新建MyWebMVCConfig类完成拦截器注册
package com.neuedu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.neuedu.interceptor.MyInterceptor;
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer{
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**").excludePathPatterns("/test");
WebMvcConfigurer.super.addInterceptors(registry);
}
}
下方代码表示向工程中添加myInterceptor拦截器,拦截范围为全部请求(/**),但排除请求(/test)
拦截范围和排除范围的参数均可以设置为字符串数组
registry.addInterceptor(myInterceptor).addPathPatterns("/**").excludePathPatterns("/test");
3.验证效果
当访问url: http://localhost:8080/myproj1/ulist 时,控制台显示如下
清空控制台信息
当访问url: http://localhost:8080/myproj1/test 时,控制台无任何信息显示
拦截器配置生效