What is the purpose of the @CrossOrigin annotation in Spring MVC?

What is the purpose of the @CrossOrigin annotation in Spring MVC?

A) To enable Cross-Origin Resource Sharing (CORS) on specific methods or classes
B) To handle cross-site scripting (XSS) attacks
C) To configure internationalization (i18n) in Spring MVC
D) To bind HTTP request parameters to method arguments

Answer:

A) To enable Cross-Origin Resource Sharing (CORS) on specific methods or classes

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.

Reference links:

Spring Boot Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top