跨域访问时很多需求,所以springboot的跨域解决也是【必须的】
1.注解方式(个人比较喜欢,方便省事)
直接添加一个注解 @CrossOrigin
如图:
2.拦截器方式
//自定义拦截器
import org.springframework.web.servlet.HandlerInterceptor;
public class CorsInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception{
String origin = httpServletRequest.getHeader("Origin");
httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin,Content-Type,Accept,token,X-Requested-With");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
return true;
}
//其他postHandle,afterCompletion空继承
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
//配置类加入自定义拦截器
@Configuration
public class MvcConfig extends WebMvcConfigurationSupport{
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new CorsInterceptor()).addPathPatterns("/**");
}
}