Spring Boot Web應(yīng)用開發(fā) CORS 跨域請(qǐng)求支持
一、Web開發(fā)經(jīng)常會(huì)遇到跨域問題,解決方案有:jsonp,iframe,CORS等等
CORS與JSONP相比
1、 JSONP只能實(shí)現(xiàn)GET請(qǐng)求,而CORS支持所有類型的HTTP請(qǐng)求。
2、 使用CORS,開發(fā)者可以使用普通的XMLHttpRequest發(fā)起請(qǐng)求和獲得數(shù)據(jù),比起JSONP有更好的錯(cuò)誤處理。
3、 JSONP主要被老的瀏覽器支持,它們往往不支持CORS,而絕大多數(shù)現(xiàn)代瀏覽器都已經(jīng)支持了CORS
瀏覽器支持情況
- Chrome 3+
- Firefox 3.5+
- Opera 12+
- Safari 4+
- Internet Explorer 8+
二、在spring MVC 中可以配置全局的規(guī)則,也可以使用@CrossOrigin注解進(jìn)行細(xì)粒度的配置。
全局配置:
@Configuration
public class CustomCorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
}
};
}
}
或者是
/**
* 全局設(shè)置
*
* @author wujing
*/
@Configuration
public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
}
}
定義方法:
/**
* @author wujing
*/
@RestController
@RequestMapping("/api")
public class ApiController {
@RequestMapping(value = "/get")
public HashMap<String, Object> get(@RequestParam String name) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title", "hello world");
map.put("name", name);
return map;
}
}
測(cè)試js:
$.ajax({
url: "http://localhost:8081/api/get",
type: "POST",
data: {
name: "測(cè)試"
},
success: function(data, status, xhr) {
console.log(data);
alert(data.name);
}
});
細(xì)粒度配置
/**
* @author wujing
*/
@RestController
@RequestMapping(value = "/api", method = RequestMethod.POST)
public class ApiController {
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "/get")
public HashMap<String, Object> get(@RequestParam String name) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title", "hello world");
map.put("name", name);
return map;
}
}
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring系列中的beanFactory與ApplicationContext
這篇文章主要介紹了Spring系列中的beanFactory與ApplicationContext,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
spring事務(wù)之事務(wù)掛起和事務(wù)恢復(fù)源碼解讀
這篇文章主要介紹了spring事務(wù)之事務(wù)掛起和事務(wù)恢復(fù)源碼解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
synchronized背后的monitor鎖實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了synchronized背后的monitor鎖實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
MyBatis實(shí)現(xiàn)動(dòng)態(tài)查詢、模糊查詢功能
這篇文章主要介紹了MyBatis實(shí)現(xiàn)動(dòng)態(tài)查詢、模糊查詢功能,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-06-06
Spring JPA學(xué)習(xí)之delete方法示例詳解
這篇文章主要為大家介紹了Spring JPA學(xué)習(xí)delete方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04

