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

使用Spring CROS解决项目中的跨域问题详解

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

使用Spring CROS解决项目中的跨域问题详解

CROS(Cross-Origin Resource Sharing) 用于解决浏览器中跨域请求的问题。简单的Get请求可以使用JSONP来解决,而对于其它复杂的请求则需要后端应用的支持CROS。Spring在4.2版本之后提供了@CrossOrigin 注解来实现对Cross的支持。

在Controller方法上配置

@CrossOrigin(origins = {"http://loaclhost:8088"})
@RequestMapping(value = "/crossTest",method = RequestMethod.GET)
public String greeting() {
  return "corss test";
}

在Controller上配置,那么这个Controller中的所有方法都会支持CORS

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@CrossOrigin(origins = "http://localhost:8088",maxAge = 3600)
@Controller
@RequestMapping("/api")
public class AppController {
  
    @RequestMapping(value = "/crossTest",method = RequestMethod.GET)
    public String greeting() {
      return "corss test";
    }
    
}

Java Config全局配置

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class SpringWebConfig extends WebMvcConfigurerAdapter {

  
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    super.addCorsMappings(registry);
    // 对所有的URL配置
    registry.addMapping("/**");

    // 针对某些URL配置
    registry.addMapping("/api/**").allowedOrigins("http:///localhost:8088")
 .allowedMethods("PUT","DELETE")
 .allowedHeaders("header1","header2","header3")
 .exposedHeaders("header1","header2")
 .allowCredentials(false).maxAge(3600);
  }
}

XML全局配置




  
    
    
  


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

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

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

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