📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
- RESTful web services should support Cross-Origin Resource Sharing.
- RESTful web service application should allow accessing the API(s) from the 8080 port.
1. Class-Level and Method-Level CORS Configuration
1.1 Spring Boot CORS – Method level with @CrossOrigin
@RestController
@RequestMapping("/api/v1")
public class TodoController {
@Autowired
private TodoRepository todoRepository;
@CrossOrigin
@GetMapping("/users/{username}/todos")
public List < Todo > getAllTodos(@PathVariable String username) {
return todoRepository.findByUsername(username);
}
}
- All headers and origins are permitted
- Credentials are allowed
- Maximum age is set to 30 minutes
- The list of HTTP methods is set to the methods on the @RequestMethod annotation
@RestController
@RequestMapping("/api/v1")
public class TodoController {
@Autowired
private TodoRepository todoRepository;
@CrossOrigin(origins = {
"http://domain1.com",
"http://domain2.com"
},
allowedHeaders = "X-AUTH-TOKEN",
allowCredentials = "false",
maxAge = 15 * 60,
methods = {
RequestMethod.GET,
RequestMethod.POST
})
@GetMapping("/users/{username}/todos")
public List < Todo > getAllTodos(@PathVariable String username) {
return todoRepository.findByUsername(username);
}
}
1.2 Spring Boot CORS – Class level with @CrossOrigin
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api/v1")
public class TodoController {
@Autowired
private TodoRepository todoRepository;
@GetMapping("/users/{username}/todos")
public List < Todo > getAllTodos(@PathVariable String username) {
return todoRepository.findByUsername(username);
}
@CrossOrigin
@GetMapping("/users/{username}/todos/{id}")
public Todo getTodo(@PathVariable String username, @PathVariable long id) {
return todoRepository.findById(id).get();
}
@DeleteMapping("/users/{username}/todos/{id}")
public ResponseEntity < Void > deleteTodo(@PathVariable String username, @PathVariable long id) {
todoRepository.deleteById(id);
return ResponseEntity.noContent().build();
}
@PutMapping("/users/{username}/todos/{id}")
public ResponseEntity < Todo > updateTodo(@PathVariable String username, @PathVariable long id,
@RequestBody Todo todo) {
Todo todoUpdated = todoRepository.save(todo);
return new ResponseEntity < Todo > (todoUpdated, HttpStatus.OK);
}
@PostMapping("/users/{username}/todos")
public ResponseEntity < Void > createTodo(@PathVariable String username, @RequestBody Todo todo) {
todo.setUsername(username);
Todo createdTodo = todoRepository.save(todo);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(createdTodo.getId())
.toUri();
return ResponseEntity.created(uri).build();
}
}
2. Spring Boot CORS - Global CORS Configuration
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(false)
.maxAge(3600);
}
}
Comments
Post a Comment
Leave Comment