SPRINGMVC 4.2 Add cross-domain support app, interface (note crossorigin)

Source: Internet
Author: User
Tags http request

What is a cross-domain


Simply put, the browser restricts access to the JS code under Site A to make an AJAX request to the URL under Site B. For example, the front-end domain name is www.abc.com, then in the current environment to run the JS code, for security reasons, access to the resources under the www.xyz.com domain name is limited. Modern browsers, by default, block cross-domain AJAX requests based on security reasons, which are a must-have feature in modern browsers, but are often inconvenient for development. Especially for the background developers like me, this thing is simply magical.


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. )

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; }
The following example uses this annotation on a method and a controller.

Using @crossorigin annotations on the controller
@CrossOrigin ()
@RestController
@RequestMapping ("/test") public
class TestController {

    @ Requestmapping ("/{id}") Public account
    Retrieve (@PathVariable Long ID) {
        //...
    }

    @RequestMapping (method = requestmethod.delete, Path = "/{id}") Public
    void Remove (@PathVariable Long ID) {
        //...
    }
}

This specifies that all the methods in the current TestController can handle requests across domains.


Using @crossorigin Annotations on methods

@RestController
@RequestMapping ("/account") public
class AccountController {

    @CrossOrigin
    @ Requestmapping ("/{id}") Public account
    Retrieve (@PathVariable Long ID) {
        //...
    }

    @RequestMapping (method = requestmethod.delete, Path = "/{id}") Public
    void Remove (@PathVariable Long ID) {
        //...
    }
}

In this example, the Retrieve method has annotations, when retrieve can be processed across domains, and remove is not processed across domains.





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.