Junior — Middle
Are specific annotations from the Spring package used with @RestController?
sobes.tech AI
Answer from AI
The @RestController annotation in Spring combines two annotations: @Controller and @ResponseBody. It is used for creating RESTful web services, where controller methods return data directly in JSON or XML format.
Specific annotations often used together with @RestController for routing and handling HTTP requests include:
@RequestMapping— for specifying the path and HTTP method (GET, POST, etc.)@GetMapping,@PostMapping,@PutMapping,@DeleteMapping— specialized shortcuts for@RequestMappingwith specific HTTP methods@PathVariable— for obtaining variables from the URL@RequestParam— for obtaining request parameters@RequestBody— for binding the request body to an object
Example:
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
// logic to get user by id
}
@PostMapping
public User createUser(@RequestBody User user) {
// logic to create user
}
}