Springboot拦截器和SpringMVC差不多,就是配置方面有点区别
- 使用注解@Configuration配置拦截器
- 继承WebMvcConfigurerAdapter
- 重写addInterceptors添加需要的拦截器地址
public class OneInterceptor implements HandlerInterceptor {
/**
* 在请求处理之前进行调用(Controller方法调用之前)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object object) throws Exception {
System.out.println("被one拦截,放行...");
return true;
/*if (true) {
returnErrorResponse(response, IMoocJSONResult.errorMsg("被one拦截..."));
}
return false;*/
}
/**
* 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object object, ModelAndView mv)
throws Exception {
// TODO Auto-generated method stub
}
/**
* 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行
* (主要是用于进行资源清理工作)
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object object, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
public void returnErrorResponse(HttpServletResponse response, IMoocJSONResult result)
throws IOException, UnsupportedEncodingException {
OutputStream out=null;
try{
response.setCharacterEncoding("utf-8");
response.setContentType("text/json");
out = response.getOutputStream();
out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
out.flush();
} finally{
if(out!=null){
out.close();
}
}
}
}
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
/**
* 拦截器按照顺序执行
*/
registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**")
.addPathPatterns("/one/**");
registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");
super.addInterceptors(registry);
}
}
一个请求可以被多个拦截器拦,一个拦截器也可以拦多个请求
拦截所有请求可以把后面的路径写成/*/**
如上,OneInterceptor放行了,TwoInterceptor拦截了没放行而是返回了一个错误信息的JsonResult
那最终还是显示JsonResult的页面