spring/spring mvc/spring boot for cross-domain

Source: Internet
Author: User

Description: Spring MVC and Spring boot actually use the same set.

CORS Introduction Please see here: Https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS

In a Web project, if we want to support cors, generally through the filter implementation, you can define some basic rules, but it is not convenient to provide a more granular configuration, if you want to reference the filter implementation, you can read the following article: http://my.oschina.net/ huangyong/blog/521891

Spring MVC adds support for cors starting with version 4.2

Adding Cors support in spring MVC is simple, you can configure global rules, or you can use @CrossOrigin annotations for fine-grained configuration.

Using @CrossOrigin annotations

First look at the attributes supported by this annotation through the source code:

@Target ({elementtype.method, elementtype.type}) @Retention (retentionpolicy.runtime) @Documented Public@Interfacecrossorigin {string[] default_origins= { "*" }; String[] Default_allowed_headers= { "*" }; BooleanDefault_allow_credentials =true; LongDefault_max_age = 1800; /*** Same as Origins property*/@AliasFor ("Origins") string[] Value ()default {}; /*** A collection of all supported domains, such as "http://domain1.com". * <p> These values are displayed in the request header Access-control-allow-origin * "*" on behalf of all domain requests are supported * <p> if not defined, all requested domains are supported *@see#value*/@AliasFor ("Value") string[] Origins ()default {}; /*** header is allowed for request headers, which is supported by default*/string[] Allowedheaders ()default {}; /*** Headers that are allowed to be accessed in the response header, default to null*/string[] Exposedheaders ()default {}; /*** Request supported methods, such as "{Requestmethod.get, Requestmethod.post}"}. * Default supports the method set in Requestmapping*/requestmethod[] Methods ()default {}; /*** Whether to allow cookies to be sent with the request, you must specify a specific domain when using*/String allowcredentials ()default""; /*** The validity of the pre-requested result, default 30 minutes*/      LongMaxAge ()default-1; }  

If you do not understand the meaning of these attributes, it is recommended to read the following article to learn more: http://fengchj.com/?p=1888

The following example Controller uses this annotation on methods and

@CrossOriginConfiguration of annotations:

@CrossOrigin (Origins = "Http://domain2.com", MaxAge = 3600) @RestController @RequestMapping ("/account")   Public classAccountController {@RequestMapping ("/{id}")       PublicAccount Retrieve (@PathVariable Long ID) {// ...  } @RequestMapping (Method= requestmethod.delete, Path = "/{id}")       Public voidRemove (@PathVariable Long ID) {// ...      }  }  

This specifies that AccountController all the methods in the current process can handle http://domain2.com requests on the domain,

To use annotations on a method @CrossOrigin :

@CrossOrigin (MaxAge = 3600) @RestController @RequestMapping ("/account")   Public classAccountController {@CrossOrigin ("Http://domain2.com") @RequestMapping ("/{id}")       PublicAccount Retrieve (@PathVariable Long ID) {// ...  } @RequestMapping (Method= requestmethod.delete, Path = "/{id}")       Public voidRemove (@PathVariable Long ID) {// ...      }  }  

In this example, there are annotations on the class as well as AccountController @CrossOrigin retrieve annotations on the method, and spring combines the attributes of the two annotations.

Cors Global Configuration, in addition to fine-grained annotation-based configurations, you might want to define some global cors configurations. This is similar to using filters, but can be declared in spring MVC and combined with fine-grained @crossorigin configurations. By default, all domain names and, and post methods are allowed.

Spring Boot configuration:

If you use spring Boot, this is a convenient way to configure it. Look at the following example:

@Configuration  @EnableWebMvc  publicclass extends  Webmvcconfigureradapter {        @Override      publicvoid  addcorsmappings ( Corsregistry registry) {          registry.addmapping ("/**");      }  }  

You can easily change any property, and configure Cors for a specific path pattern:

@Configuration @EnableWebMvc Public classWebconfigextendsWebmvcconfigureradapter {@Override Public voidaddcorsmappings (Corsregistry registry) {registry.addmapping ("/api/**"). Allowedorigins ("Http://domain2.com"). Allowedmethods ("PUT", "DELETE"). Allowedheaders ("Header1", "Header2", "Header3"). Exposedheaders ("Header1", "Header2"). Allowcredentials (false). MaxAge (3600); }  }  

XML-based configuration in Spring MVC:

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

This configuration is the same as the first of the Java methods above.

Similarly, more complex configurations can be made:

<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"/>        allowed-origins= "http://domain1.com"/>    </mvc:cors>  

Access-control-allow-origin: *: Indicates that any site is allowed to cross-domain requests for this resource

Solutions under Spring MVC:

Define Corsfilter

Importjava.io.IOException; ImportJavax.servlet.Filter; ImportJavax.servlet.FilterChain; ImportJavax.servlet.FilterConfig; Importjavax.servlet.ServletException; Importjavax.servlet.ServletRequest; ImportJavax.servlet.ServletResponse; ImportJavax.servlet.http.HttpServletResponse; Importorg.springframework.stereotype.Component; @Component Public classCorsfilterImplementsFilter { Public voidDoFilter (servletrequest req, servletresponse Res, filterchain chain)throwsIOException, servletexception {httpservletresponse response=(HttpServletResponse) res; Response.setheader ("Access-control-allow-origin", "*"); Response.setheader ("Access-control-allow-methods", "POST, GET, OPTIONS, DELETE"); Response.setheader ("Access-control-max-age", "3600"); Response.setheader ("Access-control-allow-headers", "Origin, X-requested-with, Content-type, Accept");    Chain.dofilter (req, res); }     Public voidInit (Filterconfig filterconfig) {} Public voiddestroy () {}}

Xml:

<filter>    <filter-name>cors</filter-name>    <filter-class> com.web.filter.corsfilter</filter-class>  </filter>  <filter-mapping>    <filter-name>cors</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>

Reference:

http://blog.csdn.net/z69183787/article/details/53102112 (the above content is transferred from this article)

spring/spring mvc/spring boot for cross-domain

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.