zoukankan      html  css  js  c++  java
  • spring mvc 跨域请求处理——spring 4.2 以上

    Controller method CORS configuration

    You can add to your @RequestMapping annotated handler method a @CrossOrigin annotation in order to enable CORS on it (by default @CrossOrigin allows all origins and the HTTP methods specified in the @RequestMapping annotation):

    @RestController
    @RequestMapping("/account")
    public class AccountController {
    
    	@CrossOrigin
    	@RequestMapping("/{id}")
    	public Account retrieve(@PathVariable Long id) {
    		// ...
    	}
    
    	@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    	public void remove(@PathVariable Long id) {
    		// ...
    	}
    }

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

    @CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
    @RestController
    @RequestMapping("/account")
    public class AccountController {
    
    	@RequestMapping("/{id}")
    	public Account retrieve(@PathVariable Long id) {
    		// ...
    	}
    
    	@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    	public void remove(@PathVariable Long id) {
    		// ...
    	}
    }

    In this example CORS support is enabled for both retrieve() and remove() handler methods, and you can also see how you can customize the CORS configuration using@CrossOrigin attributes.

    You can even use both controller and method level CORS configurations, Spring will then combine both annotation attributes to create a merged CORS configuration.

    @CrossOrigin(maxAge = 3600)
    @RestController
    @RequestMapping("/account")
    public class AccountController {
    
    	@CrossOrigin(origins = "http://domain2.com")
    	@RequestMapping("/{id}")
    	public Account retrieve(@PathVariable Long id) {
    		// ...
    	}
    
    	@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    	public void remove(@PathVariable Long id) {
    		// ...
    	}
    }

    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 withing Spring MVC and combined with fine-grained @CrossOrigin configuration. By default all origins and GETHEAD and POST methods are allowed.

    JavaConfig

    Enabling CORS for the whole application is as simple as:

    @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {
    
    	@Override
    	public void addCorsMappings(CorsRegistry registry) {
    		registry.addMapping("/**");
    	}
    }

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

    @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {
    
    	@Override
    	public void addCorsMappings(CorsRegistry registry) {
    		registry.addMapping("/api/**")
    			.allowedOrigins("http://domain2.com")
    			.allowedMethods("PUT", "DELETE")
    			.allowedHeaders("header1", "header2", "header3")
    			.exposedHeaders("header1", "header2")
    			.allowCredentials(false).maxAge(3600);
    	}
    }

    XML namespace

    It is also possible to configure CORS with the mvc XML namespace.

    This minimal XML configuration enable CORS on /** path pattern with the same default properties than the JavaConfig one:

    <mvc:cors>
    	<mvc:mapping path="/**" />
    </mvc:cors>

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

    <mvc:cors>
    
    	<mvc:mapping path="/api/**"
    		allowed-origins="http://domain1.com, http://domain2.com"
    		allowed-methods="GET, PUT"
    		allowed-headers="header1, header2, header3"
    		exposed-headers="header1, header2" allow-credentials="false"
    		max-age="123" />
    
    	<mvc:mapping path="/resources/**"
    		allowed-origins="http://domain1.com" />
    
    </mvc:cors>

    How does it work?

    CORS requests (including preflight ones with an OPTIONS method) are automatically dispatched to the various HandlerMappings registered. 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 (likeAccess-Control-Allow-Origin). CorsConfiguration allows you to specify how the CORS requests should be processed: allowed origins, headers, methods, etc. It can be provided in various ways:

  • 相关阅读:
    windows phone 7 客户端和web的交互(WebBrowser的使用)
    Android绑定对象到ListView中(知识积累)
    ASP.Net绑定数据到树[TreeView]献给善忘的,依然是菜鸟的我们。
    windows phone 7 通过Post提交URL到服务器,从服务器获取数据(比如登陆时候使用)
    Android从网络下载XML输出流或者字符串(知识积累)
    在GridView和Repeater上显示序号[最简单的方式,也是最实用的方式]献给善忘的依然是的菜鸟我们
    windows phone 7 通过麦克风录音,并且播放
    windows phone 7 定位(获取经纬度),然后找到经纬度所在的位置(城市信息)
    C# winform 登陆等待中. [异步请求]BackgroundWorker组件的使用
    Android解析XML之XmlPullParser
  • 原文地址:https://www.cnblogs.com/yudar/p/4828987.html
Copyright © 2011-2022 走看看