温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Springboot中怎么处理CORS跨域请求

发布时间:2021-07-08 17:30:46 来源:亿速云 阅读:168 作者:Leah 栏目:编程语言

Springboot中怎么处理CORS跨域请求,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

  一、什么是CROS?

  CORS Header

  二、SpringBoot跨域请求处理方式

  方法一、直接采用SpringBoot的注解@CrossOrigin(也支持SpringMVC)

  方法二、处理跨域请求的Configuration

  方法三、采用过滤器(filter)的方式

  总结

  先给出一个熟悉的报错信息,让你找到家的感觉~

  Access to XMLHttpRequest at 'http://192.168.1.1:8080/app/easypoi/importExcelFile' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

  一、什么是CROS?

  CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing),允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

  它通过服务器增加一个特殊的Header[Access-Control-Allow-Origin]来告诉客户端跨域的限制,如果浏览器支持CORS、并且判断Origin通过的话,就会允许XMLHttpRequest发起跨域请求。

  CORS Header

  Access-Control-Allow-Origin: http://www.xxx.com

  Access-Control-Max-Age:86400

  Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, DELETE

  Access-Control-Allow-Headers: content-type

  Access-Control-Allow-Credentials: true

  含义解释:

  CORS Header属性 解释

  Access-Control-Allow-Origin 允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求

  Access-Control-Max-Age 设置在86400秒不需要再发送预校验请求

  Access-Control-Allow-Methods 设置允许跨域请求的方法

  Access-Control-Allow-Headers 允许跨域请求包含content-type

  Access-Control-Allow-Credentials 设置允许Cookie

  二、SpringBoot跨域请求处理方式

  方法一、直接采用SpringBoot的注解@CrossOrigin(也支持SpringMVC)

  简单粗暴的方式,Controller层在需要跨域的类或者方法上加上该注解即可

  /**

  * Created with IDEA

  *

  * @Author Chensj

  * @Date 2020/5/8 10:28

  * @Description xxxx控制层

  * @Version 1.0

  */

  @RestController

  @CrossOrigin

  @RequestMapping("/situation")

  public class SituationController extends PublicUtilController {

  @Autowired

  private SituationService situationService;

  // log日志信息

  private static Logger LOGGER = Logger.getLogger(SituationController.class);

  }

  但每个Controller都得加,太麻烦了,怎么办呢,加在Controller公共父类(PublicUtilController)中,所有Controller继承即可。

  /**

  * Created with IDEA

  *

  * @Author Chensj

  * @Date 2020/5/6 10:01

  * @Description

  * @Version 1.0

  */

  @CrossOrigin

  public class PublicUtilController {

  /**

  * 公共分页参数整理接口

  *

  * @param currentPage

  * @param pageSize

  * @return

  */

  public PageInfoUtil proccedPageInfo(String currentPage, String pageSize) {

  /* 分页 */

  PageInfoUtil pageInfoUtil = new PageInfoUtil();

  try {

  /*

  * 将字符串转换成整数,有风险, 字符串为a,转换不成整数

  */

  pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));

  pageInfoUtil.setPageSize(Integer.valueOf(pageSize));

  } catch (NumberFormatException e) {

  }

  return pageInfoUtil;

  }

  }

  当然,这里虽然指SpringBoot,SpringMVC也是同样的,但要求在Spring4.2及以上的版本。另外,如果SpringMVC框架版本不方便修改,也可以通过修改tomcat的web.xml配置文件来处理,请参照另一篇博文(nginx同理)

  SpringMVC使用@CrossOrigin使用场景要求

  jdk1.8+

  Spring4.2+

  方法二、处理跨域请求的Configuration

  增加一个配置类,CrossOriginConfig.java。继承WebMvcConfigurerAdapter或者实现WebMvcConfigurer接口,其他都不用管,项目启动时,会自动读取配置。

  import org.springframework.context.annotation.Configuration;

  import org.springframework.web.servlet.config.annotation.CorsRegistry;

  import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

  /**

  * AJAX请求跨域

  * @author Mr.W

  * @time 2018-08-13

  */

  @Configuration

  public class CorsConfig extends WebMvcConfigurerAdapter {

  static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };

  @Override

  public void addCorsMappings(CorsRegistry registry) {

  registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS).maxAge(3600);

  }

  方法三、采用过滤器(filter)的方式

  同方法二加配置类,增加一个CORSFilter 类,并实现Filter接口即可,其他都不用管,接口调用时,会过滤跨域的拦截。

  @Component

  public class CORSFilter implements Filter {

  @Override

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

  throws IOException, ServletException {

  HttpServletResponse res = (HttpServletResponse) response;

  res.addHeader("Access-Control-Allow-Credentials", "true");

  res.addHeader("Access-Control-Allow-Origin", "*");

  res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

  res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");

  if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {

  response.getWriter().println("ok");

  return;

  }

  chain.doFilter(request, response);

  }

  @Override

  public void destroy() {

  }

  @Override

  public void init(FilterConfig filterConfig) throws ServletException {

  }

  }

看完上述内容,你们掌握Springboot中怎么处理CORS跨域请求的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI