- SpringBoot简单的Interceptor的配置,直接实现HandlerInterceptor接口,重写preHandle,postHandle,afterCompletion方法。
package com.bjut.config; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; /** * Created by fan on 2019/8/29. */ @Component public class TestInterceptor implements HandlerInterceptor { //视图渲染之后的操作 @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO ... } //处理请求完成后视图渲染之前的处理操作 @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO ... } //进入controller层之前拦截请求 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception { System.out.println("getContextPath:" + request.getContextPath()); System.out.println("getServletPath:" + request.getServletPath()); System.out.println("getRequestURI:" + request.getRequestURI()); System.out.println("getRequestURL:" + request.getRequestURL()); System.out.println("getRealPath:" + request.getSession().getServletContext().getRealPath("image")); // 如果不是映射到方法直接通过 if (!(obj instanceof HandlerMethod)) { return true; } HandlerMethod handlerMethod = (HandlerMethod) obj; Method method = handlerMethod.getMethod(); //检查是否有@PassToken注解 有则跳过验证 if (method.isAnnotationPresent(PassToken.class)) { PassToken passToken = method.getAnnotation(PassToken.class); if (passToken.required()) { return true; } } //检查有没有需要用户权限的注解 if (method.isAnnotationPresent(UserLoginToken.class)) { // TODO ... } return true; } }
- 除此之外,还可以自定义拦截规则,addPathPatterns 用于添加拦截规则,excludePathPatterns 用于排除拦截,如addPathPatterns("//*") 可以拦截所有请求
@Configuration public class WebMvcConfigurer extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new OneInterceptor()).addPathPatterns("/*/**").excludePathPatterns("/exclude/**"); super.addInterceptors(registry); } }
- SpringMVC 拦截 /* 和 /** 的区别:
/* : 匹配一级,即 /add , /query 等 /** : 匹配多级,即 /add , /add/user, /add/user/user… 等 /:当请求为/user/login的时候可以被拦截,当为/page/login.html页面的时候不拦截