用途:
- 日志记录
- 权限检查
- 性能监控
直接上代码:
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,请求将不再继续向下执行.
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
//Controller 执行之后被调用
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
//preHandle方法返回true, afterCompletion才会执行,可以做一些清理工作
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
*/
public class WebMvcConfig implements WebMvcConfigurer {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/**")//拦截那些请求
.excludePathPatterns("/hello");//排除哪些请求
}
}
运行结果:
hello2 被成功拦截