说明:本次的测试环境是一台电脑,启动两个springboot应用,如果是其它情况,可能稍有不同,发现时在补充吧。
方法一:给response设置header
public User getUser(HttpServletResponse response) { response.setHeader("Access-Control-Allow-Origin","*"); User user = new User(1,"张三",20); return user; }
方法二:添加注解,如果添加到类上,那么整个类中的方法都可以跨域访问
@CrossOrigin public User getUser2(HttpServletResponse response) { User user = new User(2,"李四",20); return user; }
方法三:在拦截器中设置response的header,以下是springboot中的写法
public class WebInterceptor implements HandlerInterceptor{
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { response.setHeader("Access-Control-Allow-Origin","*"); return true; } }
@Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer{ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new WebInterceptor()); } }