在springboot中实现拦截器分为两步:
1、创建普通拦截器,需要实现HandlerInterceptor并重写接口中相关方法;
2、将上一步创建的拦截器加入到springboot配置中,配置拦截规则
下面是相关代码和demo请求:
定义一个普通拦截器:
import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class DemoInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion"); } }
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; @Configuration public class InterceptorConfig implements WebMvcConfigurer { @Autowired private DemoInterceptor demoInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(demoInterceptor) // 添加拦截器 .addPathPatterns("/**") // 拦截所有请求 .excludePathPatterns("/login"); // 登陆请求不需要 } }
apifox请求
控制台打印
拦截器的典型使用场景如下:
1、权限检查,用于用户登录状态检查;
2、日志记录,记录有些接口的请求日志信息,便于信息监控
3、统一安全处理:可用于同意安全校验或参数的加解密等。
拦截器底层原理,也是利用了springAOP的面向切面编程。而AOP又是基于动态代理实现,常用的是JDK动态代理(基于反射的思想实现)
标签:拦截器,springboot,实现,springframework,org,import,servlet,public From: https://www.cnblogs.com/qwg-/p/18086741