1. 编写自定义拦截器
- 编写自定义拦截器
- 实现HandlerInterceptor接口
- 重写接口方法preHandle、postHandle、afterCompletion
如:
public class CustomInterceptor implements HandlerInterceptor {
private static final ObjectMapper mapper = new ObjectMapper();
public CustomInterceptor() {
System.out.println("init CustomInterceptor....");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// get token
String token = request.getHeader("token");
if(!StringUtils.hasLength(token)){
token = request.getParameter("token");
}
if (!StringUtils.hasLength(token)){
renderResponse(response, "token not input");
}
// verify token
User user = Cache.userCache.get(token);
if(user != null){
//token is ok
return true;
}else {
//token verify failure
//write response
//write response
renderResponse(response, "token verify failure");
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("CustomInterceptor postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("CustomInterceptor afterCompletion");
}
private void renderResponse(HttpServletResponse response, String json){
response.setCharacterEncoding("utf8");
response.setContentType("application/json");
try (PrintWriter writer = response.getWriter()) {
writer.write(mapper.writeValueAsString(JsonData.buildError(json)));
}catch (IOException e){
e.printStackTrace();
}
}
}
2. 注册拦截器
- 自定义配置类
- 配置类实现WebMvcConfigurer接口
- 重写接口方法addInterceptors
- 在addInterceptors方法中注册自定义拦截器
- 在配置类上加@Configuration注解
如:
@Configuration
public class CustomWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截器最后路径一定要 /** 如果是目录的话则是 /*/
registry.addInterceptor(getCustomInterceptor()).addPathPatterns("/api/v1/pri/**");
//register
WebMvcConfigurer.super.addInterceptors(registry);
}
/**
* put CustomInterceptor into ioc
* @return
*/
@Bean
public CustomInterceptor getCustomInterceptor(){
return new CustomInterceptor();
}
}