介绍
需要拦截器实现 Spring 提供的 HandlerInterceptor 接口并在配置文件中装配
案例
<!-- 配置拦截器栈 -->
<mvc:interceptors>
<!-- 配置具体的拦截器 -->
<mvc:interceptor>
<!-- 设置拦截的请求 -->
<mvc:mapping path="/**"/>
<!-- 排除不经过拦截器的请求 -->
<mvc:exclude-mapping path="/*/*.html"/>
<mvc:exclude-mapping path="/*/*.js"/>
<mvc:exclude-mapping path="/login"/>
<!-- 装配具体的拦截器 -->
<bean class="top.lldwb.ch09.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
/**
* 登录拦截器
* 拦截所有请求,如果未登录则返回 401 状态码
*/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
/**
* 在调用 Controller 的请求方法之前执行,如果此方法返回false,则请求就不会继续往下执行
*
* @param request current HTTP request
* @param response current HTTP response
* @param handler chosen handler to execute, for type and/or instance evaluation
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
log.info("preHandle:在调用 Controller 的请求方法之前执行,如果此方法返回false,则请求就不会继续往下执行");
if (session.getAttribute("user") == null) {
ResultVo vo = new ResultVo();
vo.setCode(HttpStatus.UNAUTHORIZED.value());
response.setContentType("application/json;charset=utf-8");
String json = new ObjectMapper().writeValueAsString(vo);
response.getWriter().println(json);
return false;
}
// return HandlerInterceptor.super.preHandle(request, response, handler);
return true;
}
/**
* 在调用 Controller 的请求方法之后返回之前执行
* (注意:前提是 Controller 能执行和 preHandle 返回 true)
*
* @param request current HTTP request
* @param response current HTTP response
* @param handler the handler (or {@link}) that started asynchronous
* execution, for type and/or instance examination
* @param modelAndView the {@code ModelAndView} that the handler returned
* (can also be {@code null})
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle:在调用 Controller 的请求方法之后返回之前执行");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
/**
* 在调用 Controller 的请求方法并返回执行
*
* @param request current HTTP request
* @param response current HTTP response
* @param handler the handler (or {@link}) that started asynchronous
* execution, for type and/or instance examination
* @param ex any exception thrown on handler execution, if any; this does not
* include exceptions that have been handled through an exception resolver
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}