In this tutorial, we are going to see How to Enable Spring Boot CORS example.
How to Enable Spring Boot CORS Example:
As part of this example, I am going to develop two different spring boot applications, one is acting as a rest service which provides simple rest end-point, and another one consumes the reset service using ajax call.
Technologies:
- Spring Boot Started WEB 2.1.5
- Java 8
- Maven
1. Spring Boot CORS Rest Service:
Creating a simple Spring Boot Rest service application.
1.1 Project Structure:

1.2 Project Dependencies:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.onlinetutorialspoint</groupId>
<artifactId>Spring-Boot-CORS-Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring-Boot-CORS-Example</name>
<description>Spring Boot CORS Example</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.3 Creating a Simple Rest Controller:
Creating a simple HelloController, which exposes a greet rest endpoint.
package com.onlinetutorialspoint.conroller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/greet")
public String greet(){
return "Hello From Spring CORS Resource";
}
}
1.4 Main class:
package com.onlinetutorialspoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootCorsExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCorsExampleApplication.class, args);
}
}
1.5 Run It:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.5.RELEASE)
2019-06-02 10:35:53.375 INFO 5164 --- [ main] c.o.SpringBootCorsExampleApplication : Starting SpringBootCorsExampleApplication on DESKTOP-RN4SMHT with PID 5164 (D:\work\Spring-Boot-CORS-Example\target\classes started by Lenovo in D:\work\Spring-Boot-CORS-Example)
2019-06-02 10:35:53.384 INFO 5164 --- [ main] c.o.SpringBootCorsExampleApplication : No active profile set, falling back to default profiles: default
2019-06-02 10:35:57.943 INFO 5164 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
As you can see, the application has been running on 8080 port.
Let’s create a client application and try access the /greet endpoint.
2. Spring Boot Client App:
Creating a simple Spring Boot Web MVC app using thymeleaf to access the above service application.
2.1 Application Structure:

2.2 Create HomeController:
Creating a simple home controller which gives /home end-point it will direct to home.html page.
package com.onlinetutorialspoint.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/home")
public String home() {
return "home";
}
}
2.3 Application.properties
Since we ran our service application on 8080 port, I am going to make this client application’s port as 8090.
server.port=8090
2.4 Thymeleaf Template:
A simple thymeleaf HTML template, providing a simple button. When clicking on the button, the corresponding click event has been handled in home.js.
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1" />
<title>Spring Boot CORS Example</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" />
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="/home.js"></script>
</head>
<body>
<br />
<br />
<div class="container" align="center">
<button id="greet" type="button" class="btn btn-primary">Greet Me</button>
</div>
<h1 id="response"></h1>
</body>
</html>
2.5 Javascript
home.js
Handling click event of the button and calling http://loalhost:8080/greet service endpoint.
GET: $(document).ready(
function() {
// GET REQUEST
$("#greet").click(function(event) {
event.preventDefault();
ajaxGet();
});
// DO GET
function ajaxGet() {
$.ajax({
url : "http://localhost:8080/greet",
success : function(result) {
$("#response").html(result);
}
});
}
})
2.6 Main-Class:
package com.onlinetutorialspoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootThymeLeafExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootThymeLeafExampleApplication.class, args);
}
}
2.7 Run It:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.5.RELEASE)
2019-06-02 10:40:12.463 INFO 12000 --- [ main] .o.SpringBootThymeLeafExampleApplication : Starting SpringBootThymeLeafExampleApplication on DESKTOP-RN4SMHT with PID 12000 (D:\work\Spring-Boot-ThymeLeaf-Example\target\classes started by Lenovo in D:\work\Spring-Boot-ThymeLeaf-Example)
2019-06-02 10:40:12.469 INFO 12000 --- [ main] .o.SpringBootThymeLeafExampleApplication : No active profile set, falling back to default profiles: default
2019-06-02 10:40:15.884 INFO 12000 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8090 (http)
Access the application using http://localhost:8090/home and click on the Greet Me button.

When you click on the above button, nothing will appear on the screen; you can see the possible errors/warnings by inspecting the browser window. Click on F12 key and go to console tab there you would know the issue saying

If you want to dig into this issue more, you can get the more about this issue here.
Let’s fix this issue by taking the advantages of Spring Framework.
3 Enable Spring Boot CORS:
Spring enables CORS by providing the @CrossOrigin annotation. This annotation makes the annotated methods/classes as permitting cross-origin requests.
Let’s permit our /greet method from cross-origin requests.
package com.onlinetutorialspoint.conroller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/greet")
@CrossOrigin(origins = "http://localhost:8090")
public String greet(){
return "Hello From Spring CORS Resource";
}
}
Output:
Now we can see the desired output.

On the above example, we have enabled the CORS for greet() method for a single domain that is http://localhost:8090. We have different configurable ways to allow it.
3.1 @CrossOrigin at Class/Controller Level:
Enabling CrossOrigin for all the methods under HelloController for the domain http://localhost:8080
package com.onlinetutorialspoint.conroller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "http://localhost:8090")
public class HelloController {
@GetMapping("/greet")
public String greet(){
return "Hello From Spring CORS Resource";
}
}
Enabling @CrossOrigin for all the methods under HelloController for all domains.
@RestController
@CrossOrigin(origins = "*")
public class HelloController {
@GetMapping("/greet")
public String greet(){
return "Hello From Spring CORS Resource";
}
}
3.2 @CrossOrigin at method Level:
Making /greek method accessible for all domains, the rest of the methods may be not accessible based on your configuration.
@RestController
public class HelloController {
@GetMapping("/greet")
@CrossOrigin(origins = "*")
public String greet(){
return "Hello From Spring CORS Resource";
}
}
3.3 @CrossOrigin at Application Level:
Create a WebMvcConfigurer bean to enable cors mapping.
Here, I am making entire application request mappings accessible for http://localhost:8080.
@Bean
public WebMvcConfigurer configurer(){
return new WebMvcConfigurer(){
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOrigins("http://localhost:8080");
}
};
}
Making entire application request mappings accessible for all origins
@Bean
public WebMvcConfigurer configurer(){
return new WebMvcConfigurer(){
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOrigins("*");
}
};
}
This is how we can enable the CROS in Spring Boot.
References:
Download Source from GIT:
Happy Learning 🙂