HandlerInterceptor 方式
@Configuration
public class WebSecurityConfig extends WebMvcConfigurationSupport {
@Qualifier("myHandlerInterceptor")
private final HandlerInterceptor handlerInterceptor;
public WebSecurityConfig(HandlerInterceptor myHandlerInterceptor) {
this.handlerInterceptor = myHandlerInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(handlerInterceptor);
// 排除拦截地址配置
addInterceptor.excludePathPatterns("/error", "/login**");
// 拦截配置
addInterceptor.addPathPatterns("/**");
}
}
@Component
@Slf4j
public class MyHandlerInterceptor implements HandlerInterceptor {
/**
* 在Controller方法调用之前调用.
* preHandle 方法是进行处理器拦截用的。 当 preHandle 返回 false 时整个请求就结束了
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
log.info("------------请求处理前--------------");
return true;
}
/**
* 在 Controller 的方法调用之后执行,且在 DispatcherServlet 进行视图的渲染之前执行
* 前提: postHandle 只会在当前这个 Interceptor 的 preHandle 方法返回true时才执行
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("------------请求处理中--------------");
}
/**
* 该方法将在整个请求完成之后,也就是 DispatcherServlet 渲染了视图执行
* 前提: preHandle 方法返回 true
* afterCompletion 方法的主要的作用: 用于清理资源的
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("------------请求处理后--------------");
}
}
HandlerInterceptorAdapter 方式
拦截器的实现也可以通过继承org.springframework.web.servlet.handler.HandlerInterceptorAdapter
来实现。
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public HandlerInterceptorAdapter handlerInterceptorAdapter() {
return new AuthorityInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(handlerInterceptorAdapter()).addPathPatterns("/**");
}
}
@Slf4j
@Component
public class AuthorityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("before...");
String reqPath = request.getServletPath();
// 进行业务判断是否需要下一步
boolean next = checkNext();
if (!next) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType("text/json;charset=utf-8");
Response result = Response.failure("权限不足");
response.getWriter().write(JSON.toJSONString(result));
return false;
}
return true;
}
}