Updated April 6, 2023
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 .//
}
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.
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:
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 –