springboot自定义拦截器的时候首先自定义拦截器类实现HandlerInterceptor接口,
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
return true;//目标方法执行之前执行该方法,一般拦截之后的业务逻辑写到这个方法里面
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
//该方法会在controller中的目标方法调用之后,视图被渲染之前调用,但是,前提是前面的preHandle返回值必须为tru才会调用此方法
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
//该方法会在整个请求结束之后,并且视图渲染之后执行,一般用于资源的释放
}
}
定义了拦截器之后,还要对拦截器进行注册,才能生效,需要定义配置类实现WebMvcConfigure接口,用里面的addInterceptors接口进行注册
import com.demo.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
}
}
这样,项目启动之后,自定义拦截器就会生效了。