1 介紹
Spring Web MVC是基於Servlet API構建的原始Web框架。
2 攔截器
2.1 定義
springmvc框架的一種攔截機制
2.2 使用
2.2.1 兩步走
- 實現HandlerInterceptor接口
- 註冊(xml或者註解 )
2.2.2 HandlerInterceptor接口
- 實現HandlerInterceptor接口
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InterceptorTest implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true; // 只有返回true纔會繼續向下執行,返回false取消當前請求
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}
- 註冊
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 註冊攔截器(掃描到攔截器)
*/
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new InterceptorTest()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
- 使用場景
攔截器可以在請求前後進行數據攔截,類似門崗,門崗一般都有檢查身份功能,對於攔截器來說,攔截器有權限校驗功能,把握請求是否可以通過,可以在裏面進行token檢驗或者其他。
性能檢測。可以在請求前後進行時間計算,檢測接口性能。
日記記錄。攔截請求數據,記錄請求參數。