在Spring Boot中配置拦截器
1.第一步创建一个类实现HandlerInterceptor
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IpInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
}
@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 {
}
实现上面三个方法
第一个就是请求进入之前要做的
第二个是请求进入以后
第三个是请求完成以后
在这三个方法中实现具体的操作
- 再写一个配置类继承WebMvcConfigurerAdapter
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import qcssc.Interceptor.IpInterceptor;
@Configuration
public class InterceptorConfigurer extends WebMvcConfigurerAdapter {
@Bean
public IpInterceptor ipInterceptor(){
return new IpInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//addPathPatterns是要拦截的路径
registry.addInterceptor(ipInterceptor()).addPathPatterns("/cqssc/**");
super.addInterceptors(registry);
}
}
这个类中需要注意一下 如果上面的拦截器中用到了依赖注入 就要写这个@Bean的注入 否则会报NPE
以上操作搞定以后拦截器就生效了
网友评论