一.首先对HandlerInterceptor进行封装,封装为MappingInterceptor.封装的方法里添加拦截器起作用的路径addPathPatterns(),及需要排除路径的方法excludePathPatterns()
public interface MappingInterceptor extends HandlerInterceptor {
String[] addPathPatterns();
String[] excludePathPatterns();
int order();
}
二.写拦截器,拦截器实现封装好的MappingInterceptor,同时在拦截器上添加@Component,作用是将该拦截器注入到容器中以方便通过@Autowired实现实例注入.
@Component
public class CrossOriginInterceptor implements MappingInterceptor {
private static final Logger logger= LoggerFactory.getLogger(CrossOriginInterceptor.class);
@Override
public String[] addPathPatterns() {
return new String[]{"/**"};
}
@Override
public String[] excludePathPatterns() {
return new String[0];
}
@Override
public int order() {
return 0;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("允许的头信息"+request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//是否允许浏览器携带用户身份信息(cookie)
response.setHeader("Access-Control-Allow-Credentials","true");
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 {
}
}
三.将拦截器注册到项目中.在类名上添加@Configuration作为配置类在启动的时候实例化好,该类需要实现WebMvcConfigurer接口,然后将写好的拦截器通过 @Autowired注解注入到当前类中,然后重写addInterceptors方法,在方法中注册拦截器,并添加需要拦截的路径及需要排除的路径,注册的顺序代表拦截器执行的顺序.WebConfigurer需要实现 WebMvcConfigurer 这个接口,并实现里面的两个方法。(在老版本的 spring-boot 中使用的是WebMvcConfigurerAdapter,新版本中已过时!!!还有不能通过继承 WebMvcConfigurationSupport 这个类来实现,这样会在某些情况下失效!!!),第二个 addInterceptors 方法用来注册添加拦截器。
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Autowired
private CrossOriginInterceptor crossOriginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(crossOriginInterceptor).addPathPatterns(crossOriginInterceptor.addPathPatterns());
}
}
原文地址:https://www.cnblogs.com/eternityz/p/12243224.html
时间: 2024-11-09 09:25:42