SpringMVC 4.2 对跨域的支持

Cross-origin resource sharing (CORS) is a W3C specification implemented by most browsers that allows you to specify in a flexible way what kind of cross domain requests are authorized, instead of using some less secure and less powerful approaches like IFRAME or JSONP. As of version 4.2, Spring MVC supports CORS out of the box. Using controller method CORS configuration with @CrossOrigin annotations in your Spring Boot application does not require any specific configuration. Global CORS configuration can be defined by registering a WebMvcConfigurer bean with a customized addCorsMappings(CorsRegistry) method:

1@Configuration 2public class MyConfiguration { 3 @Bean 4 public WebMvcConfigurer corsConfigurer() { 5 return new WebMvcConfigurerAdapter() { 6 @Override 7 public void addCorsMappings(CorsRegistry registry) { 8 registry.addMapping("/api/**"); 9 } 10 }; 11 } 12}

这里我只是引用了一段Spring Boot 文档中的介绍,完整的介绍你可以查询 Spring Framework 文档中关于 cors 的详细说明,为了方便查看,我把它放到下面直接显示: 27.1 Introduction For security reasons, browsers prohibit AJAX calls to resources residing outside the current origin. For example, as you’re checking your bank account in one tab, you could have the evil.com website open in another tab. The scripts from evil.com should not be able to make AJAX requests to your bank API (e.g., withdrawing money from your account!) using your credentials. Cross-origin resource sharing (CORS) is a W3C specification implemented by most browsers that allows you to specify in a flexible way what kind of cross domain requests are authorized, instead of using some less secured and less powerful hacks like IFRAME or JSONP. As of Spring Framework 4.2, CORS is supported out of the box. CORS requests (including preflight ones with an OPTIONS method) are automatically dispatched to the various registered HandlerMappings. They handle CORS preflight requests and intercept CORS simple and actual requests thanks to a CorsProcessor implementation (DefaultCorsProcessor by default) in order to add the relevant CORS response headers (like Access-Control-Allow-Origin) based on the CORS configuration you have provided. [Note] Since CORS requests are automatically dispatched, you do not need to change the DispatcherServlet dispatchOptionsRequest init parameter value; using its default value (false) is the recommended approach. 27.2 Controller method CORS configuration You can add an @CrossOrigin annotation to your @RequestMapping annotated handler method in order to enable CORS on it. By default @CrossOrigin allows all origins and the HTTP methods specified in the @RequestMapping annotation:

1@RestController 2@RequestMapping("/account") 3public class AccountController { 4 5 @CrossOrigin 6 @RequestMapping("/{id}") 7 public Account retrieve(@PathVariable Long id) { 8 // ... 9 } 10 11 @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") 12 public void remove(@PathVariable Long id) { 13 // ... 14 } 15}

It is also possible to enable CORS for the whole controller:

1@CrossOrigin(origins = "http://domain2.com", maxAge = 3600) 2@RestController 3@RequestMapping("/account") 4public class AccountController { 5 6 @RequestMapping("/{id}") 7 public Account retrieve(@PathVariable Long id) { 8 // ... 9 } 10 11 @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") 12 public void remove(@PathVariable Long id) { 13 // ... 14 } 15}

In the above example CORS support is enabled for both the retrieve() and the remove() handler methods, and you can also see how you can customize the CORS configuration using @CrossOrigin attributes. You can even use both controller-level and method-level CORS configurations; Spring will then combine attributes from both annotations to create merged CORS configuration.

1@CrossOrigin(maxAge = 3600) 2@RestController 3@RequestMapping("/account") 4public class AccountController { 5 6 @CrossOrigin("http://domain2.com") 7 @RequestMapping("/{id}") 8 public Account retrieve(@PathVariable Long id) { 9 // ... 10 } 11 12 @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") 13 public void remove(@PathVariable Long id) { 14 // ... 15 } 16}

27.3 Global CORS configuration In addition to fine-grained, annotation-based configuration you’ll probably want to define some global CORS configuration as well. This is similar to using filters but can be declared within Spring MVC and combined with fine-grained @CrossOrigin configuration. By default all origins and GET, HEAD, and POST methods are allowed. 27.3.1 JavaConfig Enabling CORS for the whole application is as simple as:

1@Configuration 2@EnableWebMvc 3public class WebConfig extends WebMvcConfigurerAdapter { 4 5 @Override 6 public void addCorsMappings(CorsRegistry registry) { 7 registry.addMapping("/**"); 8 } 9}

You can easily change any properties, as well as only apply this CORS configuration to a specific path pattern:

1@Configuration 2@EnableWebMvc 3public class WebConfig extends WebMvcConfigurerAdapter { 4 5 @Override 6 public void addCorsMappings(CorsRegistry registry) { 7 registry.addMapping("/api/**") 8 .allowedOrigins("http://domain2.com") 9 .allowedMethods("PUT", "DELETE") 10 .allowedHeaders("header1", "header2", "header3") 11 .exposedHeaders("header1", "header2") 12 .allowCredentials(false).maxAge(3600); 13 } 14}

27.3.2 XML namespace The following minimal XML configuration enables CORS for the /** path pattern with the same default properties as with the aforementioned JavaConfig examples:

1<mvc:cors> 2 <mvc:mapping path="/**"></mvc:mapping> 3</mvc:cors>

It is also possible to declare several CORS mappings with customized properties:

1<mvc:cors> 2 3 <mvc:mapping path="/api/**" 4 allowed-origins="http://domain1.com, http://domain2.com" 5 allowed-methods="GET, PUT" 6 allowed-headers="header1, header2, header3" 7 exposed-headers="header1, header2" allow-credentials="false" 8 max-age="123"></mvc:mapping> 9 10 <mvc:mapping path="/resources/**" 11 allowed-origins="http://domain1.com"></mvc:mapping> 12 13</mvc:cors>

27.4 Advanced Customization CorsConfiguration allows you to specify how the CORS requests should be processed: allowed origins, headers, methods, etc. It can be provided in various ways: AbstractHandlerMapping#setCorsConfiguration() allows to specify a Map with several CorsConfiguration instances mapped to path patterns like /api/**. Subclasses can provide their own CorsConfiguration by overriding the AbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest) method. Handlers can implement the CorsConfigurationSource interface (like ResourceHttpRequestHandler now does) in order to provide a CorsConfiguration instance for each request. 27.5 Filter based CORS support In order to support CORS with filter-based security frameworks like Spring Security, or with other libraries that do not support natively CORS, Spring Framework also provides a CorsFilter. Instead of using @CrossOrigin or WebMvcConfigurer#addCorsMappings(CorsRegistry), you need to register a custom filter defined like bellow:

1import org.springframework.web.cors.CorsConfiguration; 2import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 3import org.springframework.web.filter.CorsFilter; 4 5public class MyCorsFilter extends CorsFilter { 6 7 public MyCorsFilter() { 8 super(configurationSource()); 9 } 10 11 private static UrlBasedCorsConfigurationSource configurationSource() { 12 CorsConfiguration config = new CorsConfiguration(); 13 config.setAllowCredentials(true); 14 config.addAllowedOrigin("http://domain1.com"); 15 config.addAllowedHeader("*"); 16 config.addAllowedMethod("*"); 17 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 18 source.registerCorsConfiguration("/**", config); 19 return source; 20 } 21}

tips:

本文由wp2Blog导入,原文链接:http://devonios.com/springmvc-4-2-cors-support.html

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java将前端的json数组字符串转换为列表

记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang