Q1. How do you map HTTP methods in a REST controller?
Use
Example:
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping.Example:
@GetMapping("/users") public List getUsers() { ... }
@PostMapping("/users") public User createUser(@RequestBody User user) { ... }
Q2. What is @RequestBody?
It uses
It's typically used in POST and PUT methods to receive data.
@RequestBody binds the HTTP request body to a Java object.It uses
HttpMessageConverter to deserialize the request body (e.g., JSON to object).It's typically used in POST and PUT methods to receive data.
Q3. What is @ResponseBody?
It's used in traditional
@ResponseBody indicates that a method return value should be written directly to the HTTP response body (using HttpMessageConverter).It's used in traditional
@Controller methods, but @RestController makes it implicit.Q4. How do you handle path variables in REST?
Use
Example:
@PathVariable to capture values from URI template.Example:
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { ... }
Q5. How do you handle query parameters?
Use
Example:
@RequestParam.Example:
@GetMapping("/users")
public List getUsers(@RequestParam(defaultValue="1") int page) { ... }
