设置跨域拦截器
- 在拦截器包下创建跨域拦截器
/**
* 跨域拦截器
*/
@Component
public class CROSInterceptor implements HandlerInterceptor {
/**
* 进入controller层之前拦截请求
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
Object host = httpServletRequest.getHeader("host");
String origin = httpServletRequest.getHeader("Origin");
if (origin == null){
return true;
}
httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
//httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");填写*号,delete等好像不可用
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS,PATCH");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin,Content-Type,Accept,token,X-Requested-With");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
System.out.println("---------------------开始进入请求地址拦截----------------------------"+host+"==="+origin);
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
// System.out.println("--------------处理请求完成后视图渲染之前的处理操作---------------");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
// System.out.println("---------------视图渲染之后的操作-------------------------0");
}
}
- 注册拦截器 全局使用
/**
* 注册拦截器
*/
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Autowired
private CROSInterceptor crosInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(crosInterceptor).addPathPatterns("/**");
}
}
-
项目结构