Close

Spring CORS support

[Last Updated: May 3, 2017]

Following are commonly used ways to use Spring MVC CORS support:

  • Using annotation @CrossOrigin

    This annotation can be used on controller class or methods (spring mvc handlers) level. It provides various optional elements to specify Access-Control-XYZ headers. Using this annotation without any elements will allow all origins along with other suitable defaults.

  • JavaConfig configuration

    By overriding Web Mvc Configurer Adapter# add Cors Mappings( Cors Registry registry), we can bind path pattern to various CORS related configuration.

@CrossOrigin example

@Controller
public class MyWebController {

    @CrossOrigin(origins = {"http://localhost:9000"})
    @RequestMapping("/test")
    @ResponseBody
    public String handle () {
        return "test response from spring handle() method . time: " + LocalTime.now();
    }
}
@SpringBootApplication
public class ExampleMain {

    public static void main (String[] args) {
        SpringApplication.run(ExampleMain.class, args);
    }
}

To test our handler, we need to run another web application running on port 9000 which will make a request to this handler method i.e. http://localhost:8080/test. Let's use our origin application example from servlet CORS tutorial.

Run both applications and access the origin application's client.html page:

Clicking on 'Make Ajax call':

WebMvcConfigurerAdapter #addCorsMappings() Example

@SpringBootApplication
public class ExampleMain {
    
    @Bean
    public WebMvcConfigurer configure () {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings (CorsRegistry registry) {
                registry.addMapping("/test2")
                        .allowedOrigins("http://localhost:9000")
                        .allowedMethods("GET", "POST");
            }
        };
    }
    
    public static void main (String[] args) {
        SpringApplication.run(ExampleMain.class, args);
    }
}
@Controller
public class MyWebController {

    @RequestMapping("/test2")
    @ResponseBody
    public String handle2 () {
        return "test response from handle2(). time: " + LocalTime.now();
    }
}

We have to modify our client.html a little, change ajax load uri from 'test' to 'test2' and restart both applications:

Output

In above example, the setting; registry.addMapping("/**") will bind all uris to the specified CORS config.

Example Project

Dependencies and Technologies Used:

  • Spring Boot 1.4.2.RELEASE
    Corresponding Spring Version 4.3.4.RELEASE
  • spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • JDK 1.8
  • Maven 3.3.9

Spring Cors Example Select All Download
  • spring-cors-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyWebController.java
          • resources
            • public

    See Also