第一種方式是要定義的Interceptor類要實現了Spring 的HandlerInterceptor 接口,或者是這個類繼承實現了HandlerInterceptor 接口的類,比如抽象類HandlerInterceptorAdapter ;
第二種方式是實現Spring的WebRequestInterceptor接口,或者是繼承實現了WebRequestInterceptor的類。
一、編寫攔截器類實現HandlerInterceptor接口
@Configuration
public class ApiInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ApiInterceptor.class);
//攔截器的執行是在spring容器中bean初始化之前的,攔截器執行時,spring中我們定義的bean還未初始化,自然也就無法自動注入,無法使用
@Autowired
private IRedisService redisService;
/**
* 預處理回調方法,實現處理器的預處理(如檢查登陸),第三個參數爲響應的處理器,自定義Controller
* 返回值:true表示繼續流程(如調用下一個攔截器或處理器);false表示流程中斷(如登錄檢查失敗),不會繼續調用其他的攔截器或處理器,此時我們需要通過response來產生響應;
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 如果不是映射到方法直接通過
if (!(handler instanceof HandlerMethod)) {
return true;
}
//設置編碼格式
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
// 處理邏輯
// ..............
String resultStatus = JSONObject.fromObject(new
RespCodeEntity(RespCode.TOKEN_CONFLICT)).toString();
PrintWriter out = response.getWriter();
out.write(resultStatus);
out.flush();
out.close();
return false;
}
/**
* 後處理回調方法,實現處理器的後處理(但在渲染視圖之前),此時我們可以通過modelAndView(模型和視圖對象)對模型數據進行處理或對視圖進行處理,modelAndView也可能爲null。
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
}
/**
* 整個請求處理完畢回調方法,即在視圖渲染完畢時回調,如性能監控中我們可以在此記錄結束時間並輸出消耗時間,還可以進行一些資源清理,類似於try-catch-finally中的finally,但僅調用處理器執行鏈中
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e)
throws Exception {
}
}
一、配置攔截器
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
// 將攔截器bean化
@Bean
public ApiInterceptor getApiInterceptor() {
return new ApiInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(/*new APIInterceptor()*/getApiInterceptor())
.addPathPatterns("/**").excludePathPatterns("/user/login", "/user/register", "/user/verifyCode", "/user/upSoftware");
}
/* @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("index");
}*/
}
// WebMvcConfigurerAdapter 過時替代的方式:
// 1. JavaBean配置WebMvcConfigurer https://www.jianshu.com/p/77482f0b59e9
/* 2. @Configuration
public class WebMvcConfg extends WebMvcConfigurationSupport {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("index");
}
}*/
代碼註釋已經解釋很清楚了。