What is the purpose of the @CrossOrigin annotation in Spring MVC?
Answer:
Explanation:
The @CrossOrigin
annotation in Spring MVC is used to enable Cross-Origin Resource Sharing (CORS) on specific methods or classes. CORS is a security feature implemented by browsers that restricts web pages from making requests to a different domain than the one that served the web page. The @CrossOrigin
annotation allows you to configure CORS settings for your Spring MVC application, enabling it to accept requests from other domains.
For example:
@RestController
@CrossOrigin(origins = "http://example.com")
public class MyRestController {
@GetMapping("/api/data")
public String getData() {
return "This is some data";
}
}
In this example, the @CrossOrigin
annotation allows the /api/data
endpoint to accept requests from http://example.com
. You can also use @CrossOrigin
at the method level to enable CORS for specific endpoints only.
Using the @CrossOrigin
annotation is crucial when building APIs that need to be accessed from web applications hosted on different domains, ensuring that your Spring MVC application can securely handle cross-origin requests.