栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot处理CORS跨域请求的三种方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot处理CORS跨域请求的三种方法

  • Access-Control-Allow-Ori
【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】

浏览器打开:qq.cn.hn/FTf 免费领取

gin: 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层在需要跨域的类或者方法上加上该注解即可

@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继承即可。

@CrossOrigin

public class PublicUtilController {

public PageInfoUtil proccedPageInfo(String currentPage, String pageSize) {

PageInfoUtil pageInfoUtil = new PageInfoUtil();

try {

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;

@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;

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/439611.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号