简单地说 拦截器 就像是一个 门卫,让你进,你就可以进,不让你进,你就进不去
实现自定义拦截器只需要3步:
1、创建我们自己的拦截器类并实现 HandlerInterceptor 接口。 2、创建一个类继承WebMvcConfigurerAdapter,并重写 addInterceptors 方法。 2、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中(在addInterceptors方法中添加)。 PS:本文重点在如何在Spring-Boot中使用拦截器,关于拦截器的原理请大家查阅资料了解。代码示例:
InterceptorConfig.java
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.boot.SpringApplication; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;public class InterceptorConfig implements HandlerInterceptor { public static void main(String[] args) { SpringApplication.run(InterceptorConfig.class, args); }public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // TODO Auto-generated method stub 写自己需要的方法 return true;//可以通过false的话 就不让通过 } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub } } |
MyWebConfig.java
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 MyWebConfig extends WebMvcConfigurerAdapter { public void addInterceptors(InterceptorRegistry registry) { // 多个拦截器组成一个拦截器链 // addPathPatterns 用于添加拦截规则 // excludePathPatterns 用户排除拦截 registry.addInterceptor(new InterceptorConfig()).addPathPatterns("/apply/**");//自己的接口 super.addInterceptors(registry); } } |