本节我将带大家来学习一下springboot2.0中是如何整合拦截器。
我们需要引入的依赖依旧是springboot2.0父工程和web组件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
编写我们的启动类Main
/**
* @author 小吉
* @description springboot启动类
* @date 2020/5/23
*/
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class,args);
}
}
1、创建拦截器
我们通过实现HandlerInterceptor接口来做我们的拦截器,可以查看到HandlerInterceptor接口源码,该接口定义的三个方法都使用default关键字修饰,这个是JDK8新增加的特性。被default关键字修饰的方法可以不实现,可以默认使用。那么我们来重新实现一下这三个方法。
HandlerInterceptor接口源码展示(已经去除注释):
public interface HandlerInterceptor {
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return true;
}
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable ModelAndView modelAndView) throws Exception {
}
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable Exception ex) throws Exception {
}
}
MyIntercept类源码
/**
* @author 小吉
* @description springboot2.0整合拦截器
* @date 2020/5/23
*/
@Component
public class MyIntercept implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("请求执行之前拦截..." + System.currentTimeMillis());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("请求执行中..." + System.currentTimeMillis());
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("请求执行完成..." + System.currentTimeMillis());
}
}
2、注册拦截器
/**
* @author 小吉
* @description web配置
* @date 2020/5/23
*/
@Configuration
public class WebConfig {
@Autowired
private MyIntercept myIntercept;
@Bean
public WebMvcConfigurer WebMvcConfigurer() {
return new WebMvcConfigurer() {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myIntercept).addPathPatterns("/*");
};
};
}
}
将MyIntercept拦截器注册到springboot的web配置中。
3、编写控制器测试
/**
* @author 小吉
* @description 测试拦截器拦截
* @date 2020/5/23
*/
@RestController
public class HelloController {
@RequestMapping("hello")
public String hello(){
System.out.println("进入hello方法..." + System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "进入hello方法";
}
}
请求执行之前拦截...1590244547663
进入hello方法...1590244547671
请求执行中...1590244549691
请求执行完成...1590244549691