-
定义拦截器类
AppkeyInterceptor
类并实现 HandlerInterceptor 接口。 -
实现其
preHandle()
方法; -
在 preHandle 方法内通过注解和参数判断是否需要拦截请求,拦截请求时接口返回
false
; -
在自定义的
WebMvcConfigurerAdapter
类内注册此拦截器;
AppkeyInterceptor
类如下:
@Component
public class WhitelistInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Whitelist whitelist = ((HandlerMethod) handler).getMethodAnnotation(Whitelist.class);
// whitelist.values(); 通过 request 获取请求参数,通过 whitelist 变量获取注解参数
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 方法在Controller方法执行结束后执行
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在view视图渲染完成后执行
}
}
扩展
要启用 拦截器还要显式配置它启用,这里我们使用 WebMvcConfigurerAdapter
对它进行配置。需要注意,继承它的的 MvcConfiguration
需要在 ComponentScan 路径下。
@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addIntercepto