🎈博客主页:🌈我的主页🌈
🎈欢迎点赞 👍 收藏 🌟留言 📝 欢迎讨论!👏
🎈本文由 【泠青沼~】 原创,首发于 CSDN🚩🚩🚩
🎈由于博主是在学小白一枚,难免会有错误,有任何问题欢迎评论区留言指出,感激不尽!🌠个人主页
🌟 一、拦截器功能
- 日志记录
- 权限检查
- 性能监控
🌟 二、定义拦截器
首先定义一个拦截器,之后再进行配置
🌟🌟 2.1、MyIntercepter类
public class MyIntercepter implements HandlerInterceptor {
//方法返回False,请求将不会继续进行
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
//Controller执行之后被调用
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
//preHandle方法返回true后,afterCompletion才会执行
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}
🌟🌟 2.2、MyWebMvcConfig类
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyIntercepter())
//拦截所有路径的请求
.addPathPatterns("/**")
//放行/hello的请求
.excludePathPatterns("/hello");
}
}
🌟🌟 2.3、测试类
@RestController
public class HelloController {
@GetMapping("/hello")
public void getHello1(){
System.out.println("hello1");
}
@GetMapping("/hello1")
public void getHello2(){
System.out.println("hello2");
}
}
访问请求/hello1时:
访问请求/hello时: