Spring Web MVC是基于Servlet API构建的原始Web框架。
springmvc框架的一种拦截机制
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检验或者其他。
性能检测。可以在请求前后进行时间计算,检测接口性能。
日记记录。拦截请求数据,记录请求参数。