Cross-domain (CORS) support: The Spring Framework 4.2GA provides the first type of support for CORS, making it easier and more powerful to configure than usual filter-based solutions. As a result, Spring MVC versions will only support @crossOrigin at 4.2 or higher

Two, use method: You can add an @crossOrigin annotation handler method to enable CORS (by default, @crossOrigin allows all sources and HTTP methods to be specified in the @RequestMapping annotation) :

@RestController

@RequestMapping(“/account”) public class AccountController {

@CrossOrigin
@GetMapping("/{id}") public Account retrieve(@PathVariable Long id) { // ...

}

@DeleteMapping("/{id}") public void remove(@PathVariable Long id) { // ...

}} where @crossLogin has two arguments:

Origins: A list of domains that are allowed to access

MaxAge: The maximum time, in seconds, that the cache lasts before preparing a response.

1.2. Enable @crossLogin for the entire Controller

@CrossOrigin(origins = “http://domain2.com”, maxAge = 3600)

@RestController

@RequestMapping(“/account”) public class AccountController {

@GetMapping("/{id}") public Account retrieve(@PathVariable Long id) { // ...

}

@DeleteMapping("/{id}") public void remove(@PathVariable Long id) { // ...

}} In this example, cross-domain support is enabled for both the retrieve() and remove() processing methods, and you can also see how to customize the CORS configuration using the @crossOrigin attribute.

1.3 Using both Controller and method-level CORS configurations, Spring will merge the two annotation properties to create the merged CORS configuration.

@CrossOrigin(maxAge = 3600)

@RestController

@RequestMapping(“/account”) public class AccountController {

@CrossOrigin(origins = "http://domain2.com") @GetMapping("/{id}") public Account retrieve(@PathVariable Long id) { // .

}

@DeleteMapping("/{id}") public void remove(@PathVariable Long id) { // ...

If you are using Spring Security, be sure to enable CORS at the Spring Security level and allow it to take advantage of the configuration defined at the Spring MVC level.

@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override protected void configure(HttpSecurity http) throws Exception {
    http.cors().and()...
}

In addition to fine-grained, annotation-based configurations, you may need to define some global CORS configurations. This is similar to using a filter, but you can declare it as Spring MVC and combine it with a fine-grained @crossLogin configuration. By default, all origins and GET, HEAD and POST methods are allowed.

JavaConfig

Simplify the CORS for the entire application to:

@Configuration

@EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter {

@Override public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**");
}

} If you are using Spring Boot, it is recommended to declare the WebMVCConfigurer bean as follows:

@Configuration public class MyConfiguration {

@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); }}; }

} You can easily change any property, and only apply this CORS configuration to a specific path pattern:

@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);

} If you are using Spring Security, be sure to enable CORS at the Spring Security level and allow it to take advantage of the configuration defined at the Spring MVC level.

3. XML namespaces can also be configured with CORS and MVC XML namespaces.

A. If all methods of the entire project are accessible, this can be configured; This minimum XML configuration gives CORS the same default properties as JavaConfig in /** path mode:

<mvc:cors>

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

> It means that no matter how many layers follow it, it will match. *

Such as:

<mvc:cors>

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

>

/api/aaa

/ API/BBBB does not match:

/ API /aaa/ BBB: / API /aaa/ BBB: / API /aaa/ BBB: / API /aaa/ BBB: / API /aaa/ BBB

<mvc:cors>

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

B, You can also declare several CORS mappings with custom attributes:

<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" />

request path has/API /, method example:

@RequestMapping(“/api/crossDomain”)

@ResponseBody public String crossDomain(HttpServletRequest req, HttpServletResponse res, String name){

... ...

} c, If using Spring Security, don’t forget to enable CORS at the Spring Security level:

<http>

<! -- Default to Spring MVC's CORS configuration --> <cors /> ... </http>

4, How does it work? CORS requests (including preselected methods with options) are automatically sent to the various handlerMappings registered. They handle CORS prepare requests and intercept CORS simple and real requests, thanks to the CorsProcessor implementation (which defaults to DefaultCorsProcessor by default), To add relevant CORS response headers (such as Access-Control-Allow-Origin). CORSConfiguration allows you to specify how CORS requests should be handled: allow origins, headers, methods, and so on.

A, AbstracThandlerMapping# setCorsConfiguration() allows you to specify a mapping where several CorsConfiguration are mapped to the path mode, such as/API /**.

B. Subclasses can provide their own CorsConfiguration by overriding the getCorsConfiguration(Object, HttpServletRequest) method of the AbstractHandlerMapping class.

C, the handler can realize CorsConfigurationSource interface (e.g., ResourceHttpRequestHandler), in order to provide a CorsConfiguration for each request.

Filter-based CORS support As an alternative to the other methods described above, the Spring framework also provides CorsFilter. In this case, instead of using @CrossLogin or WebMVCConfigurer # AddCorsmappings (CorsRegistry), for example, the following filter could be declared in the Spring Boot application:

@Configuration public class MyConfiguration {

@Bean public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://domain1.com");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0); return bean;
}

Spring MVC supports @crossLogin until version 4.2 or higher. Spring MVC does not support @crossLogin until version 4.2 or higher

2. The non-@crossOrigin does not solve the cross-domain request problem, but the incorrect request leads to the failure to get the expected response, causing the browser side to indicate the cross-domain problem.

3. After adding the @CrossOrigin annotation above the Controller annotation, there is still a cross-domain problem. One solution is:

The @RequestMapping annotation does not specify GET and POST. Once specified, the problem will be solved.

The code looks like this:

@CrossOrigin

@RestController public class person{

@RequestMapping(method = RequestMethod.get) public String Add () {//

}} four, refer to the article: 1, the official documentation https://spring.io/blog/2015/0…

2, http://fanshuyao.iteye.com/bl…

2, https://blog.csdn.net/taiyang…

3, https://blog.csdn.net/snowin1…