EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring Boot cors
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring Boot cors

Spring Boot cors

Definition on Spring Boot cors

In Spring boot we have cors which stands for Cross-Origin Resource Sharing, it basically means that the host which is representing the UI, and the host which serves the data both are different. Means both are running on a different host, in such type of cases we may encounter this problem which running the application. Let’s say we have one application in angular which runs on a different host, and the backend is in spring boot which runs on a different host, so while making any request for data to the backend we may encounter this error in the console. It is a very common and very well-known term in spring boot. Spring boot provides us good support to configure this for any web application or spring. In the coming section of the tutorial, we will see how we can implement this in spring boot, and what necessary actions we need to take in order to implement in order to get a better understanding.

Syntax:

As we discussed in spring boot we have to make changes to the application in order to make this enable, let’s see a closer look at the annotation which needs to be used in this case to make this work see below;

@CrossOrigin
@RestController
@RequestMapping("/your_mapping")
public class Your_controlle {
// your logic goes here .//
}

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

As you can see in the above syntax we have just used a single annotation to make this work. we can use this annotation at the method or class level. That we will discuss in the coming section of the tutorial how to do it, is easy to use and handle.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,754 ratings)

How does Spring Boot cors works?

As of now we already know that it is a mechanism that we need to enable into our application when the UI a data server running on a different host. Let’s for understanding take an example of angular and spring boot application which runs on the different host, so whenever we try to make calls to the backend for data from frontend we may encounter this issue in the console. But in spring boot we have very good support for this without doing much more configuration inside the application before we have to add the filter to overcome this issue. In this section, we will see how we can add enable this CROS to our application just by using the annotation provided by the spring boot framework. Let’s take a closer look at each of them in detail see below;

1) Use @CrossOrigin at method level: In spring boot we can annotate our handler method with this annotation, so spring boot will handle this for us. Inside the controller class, we can annotate our method with this annotation, and specify the path of the request. So whenever the call makes to this method it will handle this. Let’s take a closer look at the reference code to understand the code as well see below;
e.g. :

@RestController
@RequestMapping("/demo")
public class DemoController {
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, path = "/{empid}")
public Employee getEMployee(@PathVariable Long empid) {
// logic goes here ..//
}
}

In the above reference code, we have used the @CrossOrigin annotation at the method of the controller, also we have not yet specified the values for the @CrossOrigin at method so it will use all the default property. All the Origin will be allowed here and whenever the request received for this method it will work.

2) Use @CrossOrigin at the controller level: We can also use the @CrossOrigin at the controller level, we can annotate our controller class with the help of this annotation and it will take care of all the things for us. But here we have to mention some of the property inside the @CrossOrigin but that is also not at all mandatory. Let’s take a look at the code for reference for better understanding of it to see below;

e.g. :

@CrossOrigin(origins = "your host", maxAge = 3600)
@RestController
@RequestMapping("/demo")
public class DemoController {
@RequestMapping(method = RequestMethod.GET, path = "/{empid}")
public Employee get(@PathVariable Long empid) {
// ... logic goes here ..//
}
@RequestMapping(method = RequestMethod.POST, path = "/create")
public void create(@RequestBody Employee emp) {
// ... logic goes here ..//
}
}

As you can see in the above line of code, we have annotated the controller with the @CrossOrigin annotation so we do not have to mark all the methods individually here, also we can specify the details inside the annotation like origin and maxAge, etc. This is the basic configuration that we have to make to enable an application to accept the request from a cross-origin or different host. This is very easy and it has not done such a heavy configuration to make this work. Also, it is very readable to the developers. In the coming section of the tutorial, we will see the example to implement this in our actual spring boot application.

Example

1) Create the spring boot project from the spring initializer and provide the needed input there.

URL : https://start.spring.io/

2) import this inside the editor you use. No other dependency needs to be added to make this run.

3) Create one controller and add this annotation at the top of it.

e.g. :

@CrossOrigin
@RestController
@RequestMapping("/demo")
public class DemoController {
@GetMapping("/gettest/{test}")
public ResponseEntity<String> get(@PathVariable String test) {
hardDriveService.getm();
return new ResponseEntity<>("I am get method " + test, HttpStatus.OK);
}
@PostMapping("/postMethod")
public ResponseEntity<String> post() {
return new ResponseEntity<>("I am post method " , HttpStatus.OK);
}
@DeleteMapping("/deleteMethod")
public ResponseEntity<String> delete() {
return new ResponseEntity<>("I am deleteMethod method " , HttpStatus.OK);
}
}

4) And now run the mainspring application to see changes and it should run fine.

e.g. :

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

Output:

spring

Conclusion

As you can see we have enabled CROS in spring boot just by adding the simple annotation in our controller, now the hostname can be different while making requests to data from the server.

Recommended Articles

This is a guide to Spring Boot cors. Here we discuss the Definition, syntax, How Spring Boot cors works? examples with code implementation. You may also have a look at the following articles to learn more –

  1. Spring Boot OAuth2
  2. Spring Boot HTTPS
  3. Spring Boot Change Port
  4. Spring Boot JPA
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more