SpringBoot 配置拦截器
SpringBoot 配置拦截器
用途:
- 日志记录
- 权限检查
- 性能监控
直接上代码:
MyInterceptor.java
package com.zhuantai.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author ANTIA1
* @date 2021/7/8 12:49
*/
public class MyInterceptor 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");
}
}
WebMvcConfig.java
package com.zhuantai.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author ANTIA1
* @date 2021/7/8 12:54
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/**")//拦截那些请求
.excludePathPatterns("/hello");//排除哪些请求
}
}
运行结果:
hello2 被成功拦截