Springboot攔截器的簡單演示
阿新 • • 發佈:2018-11-26
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的頁面