SpringBoot 使用拦截器步骤为:
1、按照Spring mvc的方式编写一个拦截器类;
创建一个interceptor包
LoginInterceptor:
package com.springboot.web.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
//主要是这个方法中实现拦截逻辑
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("已经进入拦截器");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
2、编写一个配置类继承WebMvcConfigurerAdapter类
3、为该配置类添加@Configuration注解,标注此类为一个配置类,让Spring boot 扫描到;
4、覆盖其中的addInterceptors方法并添加已经编写好的拦截器:
代码如下:
编写WebConfig配置类
package com.springboot.web.config;
import com.springboot.web.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration //一定要加上这个注解,成为Springboot的配置类,不然不会生效
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
String[] addPathPatterns = {//拦截所有请求
"/*"
};
String[] excludePatterns = {//不拦截sayHi这个请求 【http://localhost:8080/sayHi】
"/sayHi"
};
//如果有多个拦截器,可以继续添加
registry.addInterceptor(new LoginInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePatterns);
}
}
测试下:
【http://localhost:8080/config】会打印“已经进入拦截器”,说明拦截器生效
【http://localhost:8080/sayHi】不会打印,说明不拦截配置生效。