介绍
今天就跟大家聊聊有关如何在春天横项目中解决跨域问题,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
横(跨源资源共享)用于解决浏览器中跨域请求的问题。简单的得到请求可以使用JSONP来解决,而对于其它复杂的请求则需要后端应用的支持CROS.Spring在4.2版本之后提供了@CrossOrigin注解来实现对十字架的支持。
在控制器方法上配置
@CrossOrigin (origins =, {“http://loaclhost: 8088“}) @RequestMapping (value =,“/crossTest", method =, RequestMethod.GET) public String 问候(),{ return 才能“corss  test"; }
在控制器上配置,那么这个控制器中的所有方法都会支持歌珥
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 问候(),{ ,,,,,return “corss test"; ,,,} ,,,, }
Java配置全局配置
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} ,,*,& lt; p>却;能够implementation is 空的。 ,,* ,,*,@param 注册表 ,,*/@Override才能 public 才能;void  addCorsMappings (CorsRegistry 注册),{ ,,,super.addCorsMappings(注册表); ,,,//,对所有的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全局配置
& lt; ? xml version=?.0“,编码=癠TF-8" ?比; http://www.springframework.org/schema/beans" & lt; beans  xmlns=?; ,,,xmlns: xsi=癶ttp://www.w3.org/2001/XMLSchema-instance" ,,,xmlns: mvc=癶ttp://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"比; & lt;才能mvc: cors> ,,,& lt; !——& lt; mvc: mapping 路径=啊?祝辞——比; ,,,& lt; mvc: mapping 路径=?api/* *”; ,,,,,,,,,,allowed-origins=癶ttp://localhost: 8088年,http://localhost: 8888“; ,,,,,,,,,,allowed-methods=? PUT" ,,,,,,,,,,allowed-headers=癶eader1, header2" ,,,,,,,,,,exposed-headers=癶eader1, header2" ,,,,,,,,,,allow-credentials=癴alse" ,,,,,,,,,,信息=?600“,/比; & lt;才能/mvc: cors> & lt;/beans>
看完上述内容,你们对如何在春天横项目中解决跨域问题有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。