您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)如何在Spring CROS項目中解決跨域問題,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
CROS(Cross-Origin Resource Sharing) 用于解決瀏覽器中跨域請求的問題。簡單的Get請求可以使用JSONP來解決,而對于其它復(fù)雜的請求則需要后端應(yīng)用的支持CROS。Spring在4.2版本之后提供了@CrossOrigin 注解來實現(xiàn)對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 { /** * {@inheritDoc} * <p>This implementation is empty. * * @param registry */ @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全局配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:cors> <!--<mvc:mapping path=""/>--> <mvc:mapping path="/api/**" allowed-origins="http://localhost:8088,http://localhost:8888" allowed-methods="GET,PUT" allowed-headers="header1,header2" exposed-headers="header1,header2" allow-credentials="false" max-age="3600" /> </mvc:cors> </beans>
看完上述內(nèi)容,你們對如何在Spring CROS項目中解決跨域問題有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。