SpringBoot配置攔截器的示例
阿新 • • 發佈:2020-11-09
在SpringBoot中配置攔截器,主要有下面兩個步驟:
1、繼承介面HandlerInterceptor,根據需要重寫其中的三個類。
2、在配置類中注入該類。
public class MyInterceptor implements HandlerInterceptor { //controller執行之前 @Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception { System.out.println("preHandler......"); return true; } //執行完controller執行之後、檢視渲染前呼叫,可以在該方法裡獲取或者修改model @Override public void postHandle(HttpServletRequest request,Object handler,ModelAndView modelAndView) throws Exception { System.out.println("postHandler......"); } //一般用於清理資源 @Override public void afterCompletion(HttpServletRequest request,Exception ex) throws Exception { System.out.println("afterCompletion......"); } }
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //1、全部攔截 // registry.addInterceptor(myInterceptor()).addPathPatterns("/**"); //2、攔截指定路徑 registry.addInterceptor(myInterceptor()).addPathPatterns("/hello"); } @Bean MyInterceptor myInterceptor(){ return new MyInterceptor(); } }
寫個controller測試一下
@RestController public class HelloController { @RequestMapping("/hello") public String hello(){ System.out.println("hello"); return "hello"; } @RequestMapping("/world") public String world(){ System.out.println("world"); return "world"; } }
測試結果:
preHandler......
hello
postHandler......
afterCompletion......
world
SpringBoot中還有一終攔截器,WebRequestInterceptor
public class MyWebRequestInterceptor implements WebRequestInterceptor { @Override public void preHandle(WebRequest webRequest) throws Exception { } @Override public void postHandle(WebRequest webRequest,ModelMap modelMap) throws Exception { } @Override public void afterCompletion(WebRequest webRequest,Exception e) throws Exception { } }
和HandlerInterceptor比較相似,但是可以發現,該攔截器的preHandler返回值為空,說明該方法並不影響後面方法的執行。那麼這個攔截器存在的目的是什麼吶?
點進WebRequest:
public interface WebRequest extends RequestAttributes { @Nullable String getHeader(String var1); @Nullable String[] getHeaderValues(String var1); Iterator<String> getHeaderNames(); @Nullable String getParameter(String var1); @Nullable String[] getParameterValues(String var1); Iterator<String> getParameterNames(); Map<String,String[]> getParameterMap(); Locale getLocale(); String getContextPath(); @Nullable String getRemoteUser(); @Nullable Principal getUserPrincipal(); boolean isUserInRole(String var1); boolean isSecure();
發現對reques請求中引數做了進一步處理(@Nullable表示可以為空),更加的方便呼叫。所以兩個攔截器的側重點不同,HandlerInterceptor功能較為強大,可以攔截請求,可以實現WebRequestInterceptor的所有功能,只是要寫的邏輯程式碼要多一點。更而WebRequestInterceptor傾向於簡化獲取request引數的過程以及預設引數供後面的流程使用。
以上就是SpringBoot配置攔截器的示例的詳細內容,更多關於SpringBoot配置攔截器的資料請關注我們其它相關文章!