Spring MVC 4.2 adds CORS support

Source: Internet
Author: User
Tags http request in domain
Spring MVC 4.2 adds CORS support

Cross-Site HTTP requests (Cross-site HTTP request) refer to the domain of the resource originating the request that is different from the HTTP request for the domain in which the request is pointing. For example, a WEB application in Domain A (http://domaina.example) introduces a picture resource (http://domainb.foo/image.jpg) from the domain name B (http://domainb.foo) site via tags. The Web app for domain A will cause the browser to initiate a cross-site HTTP request. In today's WEB development, the use of cross-site HTTP requests to load a variety of resources, including CSS, graphics, JavaScript scripts, and other classes of resources, has become a common and popular way.

As you know, the browser restricts the cross-site requests that originate in the script for security reasons. For example, using the XMLHttpRequest object to initiate an HTTP request must follow the same Origin policy (Same-origin). Specifically, a WEB application can only initiate an HTTP request to the source domain name it loads by using the XMLHttpRequest object, and cannot initiate a request to any other domain name. In order to develop a more powerful, richer, and more secure Web application, developers are eager to become more and more powerful and richer in Web applications without losing security. For example, you can use XMLHttpRequest to initiate a cross-site HTTP request. (This paragraph describes the cross-domain inaccuracy, cross-domain not the browser restricts the originating of cross-site requests, but the cross-site requests can be initiated normally, but the returned results are blocked by the browser.) The best example is the CRSF cross-site attack principle, where the request is sent to the backend server regardless of whether it is cross-domain. Note: Some browsers do not allow cross-domain access to HTTP from an HTTPS domain, such as Chrome and Firefox, which is a special case when requests are intercepted when the request is not issued. )

For more information about cors, 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, it is generally done through a filter, 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 @interface

    Crossorigin {string[] default_origins = {"*"};

    String[] Default_allowed_headers = {"*"};

    Boolean default_allow_credentials = true;


    Long default_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 support * @see #val

    UE */@AliasFor ("value") string[] Origins () default {};

    /** * Allow header to request headers, default */string[] Allowedheaders ()

    /** * The header that is allowed to be accessed in the response header, default is empty */string[] Exposedheaders () defaults {};
     /** * Request supported methods, such as "{Requestmethod.get, Requestmethod.post}"}.

    * Default supports the method set in Requestmapping */requestmethod[] methods () "Default {}; /** * Whether the cookie is allowed to be sent with the request,You must specify a specific domain */String allowcredentials () default "";

/** * The validity period of the pre-requested result, default 30 minutes */Long MaxAge () default-1; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

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 uses this annotation on a method and a controller. using @crossorigin Annotations on the 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, Path = "/{id}") Public
    void Remove (@PathVariable Long ID) {
        //: .
    }
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

This specifies that all methods in the current AccountController can handle requests on the http://domain2.com domain and use @crossorigin annotations on methods

@CrossOrigin (maxAge = 3600)
@RestController
@RequestMapping ("/account") Public
class AccountController {

    @CrossOrigin ("http://domain2.com")
    @RequestMapping ("/{id}") Public account
    Retrieve (@PathVariable Long ID) {
        //...
    }

    @RequestMapping (method = requestmethod.delete, Path = "/{id}") Public
    void Remove (@PathVariable Long ID) {
        //. ..
    }
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

In this example, there are @crossorigin annotations on the AccountController class as well as annotations on the retrieve 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 of the 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. Java-based configuration

Look at the following example:

@Configuration
@EnableWebMvc Public
class Webconfig extends Webmvcconfigureradapter {

    @Override
    public void Addcorsmappings (Corsregistry registry) {
        registry.addmapping ("/**");
    }
}
1 2 3 4 5 6 7 8 9

You can easily change any properties and configure cors for 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);
    }
}
1 2 3 4 5 6 7 8 9 10

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.