Spring MVC cross-domain request processing--spring 4.2 or more

Source: Internet
Author: User

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 allo WS all Origins and the HTTP methods specified in the @RequestMapping annotation):

@RestController@RequestMapping("/account")Public Class AccountController {@CrossOrigin@RequestMapping("/{id}")Public AccountRetrieve(@PathVariable LongId) {// ...} @RequestMapping  ( Method = requestmethod., value =  "/{id}" public void  Remove ( @PathVariable   Long Id)  {//... }}       /span>                

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 AccountRetrieve(@PathVariable LongId) {// ...} @RequestMapping  ( Method = requestmethod., value =  "/{id}" public void  Remove ( @PathVariable   Long Id)  {//... }}       /span>                

In this example CORS retrieve() remove() are enabled for both and handler methods, and can also see how can Customi Ze the CORS configuration using @CrossOrigin attributes.

You can even with both controller and method level CORS configurations, Spring would 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 AccountRetrieve(@PathVariable LongId) {// ...} @RequestMapping  ( Method = requestmethod., value =  "/{id}" public void  Remove ( @PathVariable   Long Id)  {//... }}       /span>                
Global CORS Configuration

In addition to fine-grained, annotation-based configuration you ' ll probably want to define some global CORS configuration as well. This was similar to using filters but can being declared withing Spring MVC and combined with fine-grained @CrossOrigin configuration . By default all Origins GET and, HEAD and POST methods is allowed.

Javaconfig

Enabling CORS for the whole application are as simple as:

@Configuration@EnableWebMvcpublic class webconfig  extends webmvcconfigureradapter { @Override public void addcorsmappings  (corsregistry Registry)  {registry.}}          /span>                

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

@Configuration@EnableWebMvcPublic Class Webconfig Extends Webmvcconfigureradapter {@OverridePublic voidAddcorsmappings(CorsregistryRegistry) {Registry.Addmapping("/api/**").Allowedorigins("Http://domain2.com").Allowedmethods("PUT", "DELETE"). ( "header1" ,  "Header2" ,  "Header3" . ( "header1" ,  "Header2" ) .false3600}}          /span>                 
XML namespace

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

This minimal XML configuration enable CORS in /** 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" < Span class= "ATN" >max-age= "123"  />< Span class= "PLN" ><mvc:mapping path=< Span class= "ATV" > "/resources/**" allowed-origins=  "http://domain1.com"  /></MVC:CORS>              
How does does it work?

CORS requests (including preflight ones with an OPTIONS method) is automatically dispatched to the various HandlerMapping s Registere D. They handle cors preflight requests and intercept cors simple and actual requests thanks to a corsprocessor implementat Ion (Defaultcorsprocessor by default) in order to add the relevant CORS response headers (like Access-Control-Allow-Origin ). Corsconfiguration allows specify how the CORS requests should is processed:allowed origins, headers, methods, etc. It can provided in various ways:

    • AbstractHandlerMapping#setCorsConfiguration()Allows to specify a with Map severalcorsconfiguration mapped on path patterns like/api/**
    • Subclasses can provide their own by CorsConfiguration overriding AbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest) method
    • Handlers can implement CorsConfigurationSource interface (like Today ResourceHttpRequestHandler does) in order to provide a corsconfiguration for each request.

Spring MVC cross-domain request processing--spring 4.2 or more

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.