How to Enable Spring Boot CORS Example - Spring Boot @CrossOrigin

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see 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.
Spring Boot Started WEB 2.1.5
Java 8
Maven
Creating a simple Spring Boot Rest service application.
<?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>

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";
    }
}

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

}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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.
Creating a simple Spring Boot Web MVC app using thymeleaf to access the above service application.
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";
    }

}
Since we ran our service application on 8080 port, I am going to make this client application’s port as 8090.
server.port=8090
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>
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);
          }
        });
      }
})
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);
  }

}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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.
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.
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";
    }
}
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";
    }
}
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.
CORS missing
W3.org CORS
Happy Learning 🙂

Simple Spring Boot Example
Spring Boot Kafka Producer Example
SSL Spring Boot HTTPs Enabling Example
How to set Spring Boot SetTimeZone
Spring Boot Apache ActiveMq In Memory Example
How to Get All Spring Beans Details Loaded in ICO
External Apache ActiveMQ Spring Boot Example
Step By Step Spring Boot Docker Deployment Example
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot Basic Authentication Example
How to enable Swagger in Spring Boot Application
Spring Boot MongoDB + Spring Data Example
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example

Simple Spring Boot Example
Spring Boot Kafka Producer Example
SSL Spring Boot HTTPs Enabling Example
How to set Spring Boot SetTimeZone
Spring Boot Apache ActiveMq In Memory Example
How to Get All Spring Beans Details Loaded in ICO
External Apache ActiveMQ Spring Boot Example
Step By Step Spring Boot Docker Deployment Example
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot Basic Authentication Example
How to enable Swagger in Spring Boot Application
Spring Boot MongoDB + Spring Data Example
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment