@Controller@Controller는 웹 애플리케이션에서 뷰(View)를 반환하는데 주로 사용@RestController는 JSON, XML과 같은 데이터를 반환하며, 뷰를 렌더링하지 않습니다.@RestController는 @Controller와 @ResponseBody를 결합한 형태입니다.@Controller
@ResponseBody
public class MyController{
}위 코드를 단순화한 것이 @RestController입니다.@RestController
@RequestMapping("/api/users")
public class UserController{
@GetMapping
public List<User> getUsers(){
return List.of(
new User(1, "mangez1", "mangez1@example.com"),
new User(2, "mangez2", "mangez2@example.com"_
);
}
@PostMapping
public User createUser(@RequestBody User user){
return user;
}
}@RestController는 요청 데이터를 처리하고 적절한 응답을 생성하여 반환합니다.@RestController@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping 각 어노테이션은 특정 HTTP 메서드에 매핑됩니다.@RequestBody@PostMapping
public User createUser(@RequestBody User user){
return user;
}@PathVariable@GetMapping("/{id}")
public User getUserById(@PathVariable int id){
return new User(id, "mangez", "mangez@example.com");
}@RequestParam@GetMapping
public List<User> getUsers(@RequestParam String role){
return userService.findByRole(role);
}@ResponseStatus@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteUser(@PathVariable int id){
userService.delete(id);
}@ResponseBody를 따로 선언하지 않아도 데이터를 반환할 수 있습니다.RESTful API의 설계 원칙을 기반으로 통신이 이루어집니다.
@ControllerAdvice를 활용하여 전역적으로 예외를 처리합니다.