@Controller:
ModelAndView 객체나 뷰(View)의 이름을 반환하여 HTML 페이지를 렌더링하는 데 사용됩니다.@RestController:
@Controller와 @ResponseBody를 합친 어노테이션입니다.@RequestMapping:
HTTP 메서드별 매핑 어노테이션 (축약형):
@RequestMapping을 더 명확하고 간결하게 사용하기 위한 어노테이션들입니다.@GetMapping: HTTP GET 요청을 처리 (데이터 조회)@PostMapping: HTTP POST 요청을 처리 (데이터 생성)@PutMapping: HTTP PUT 요청을 처리 (데이터 전체 수정)@PatchMapping: HTTP PATCH 요청을 처리 (데이터 일부 수정)@DeleteMapping: HTTP DELETE 요청을 처리 (데이터 삭제)@RestController
@RequestMapping("/api/users") // 공통 경로
public class UserController {
@GetMapping("/{userId}") // GET /api/users/{userId}
public User getUser(@PathVariable Long userId) {
// ... 사용자 조회 로직 ...
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody UserCreateRequest request) {
// ... 사용자 생성 로직 ...
}
}
| 어노테이션 | 데이터 위치 | 설명 | 예시 |
|---|---|---|---|
@PathVariable | URL 경로 | URL 경로의 일부를 변수로 받음. (e.g., /users/123) | @GetMapping("/{id}") public User getUser(@PathVariable Long id) |
@RequestParam | 쿼리 파라미터 | URL의 ? 뒤에 오는 Key-Value 쌍을 받음. (e.g., /search?keyword=java) | @GetMapping("/search") public List<Item> search(@RequestParam String keyword) |
@RequestBody | HTTP Body | 요청의 본문에 담긴 JSON, XML 등의 데이터를 Java 객체(DTO)로 변환하여 받음. (주로 POST, PUT 요청) | @PostMapping public void createUser(@RequestBody UserDto userDto) |
@ModelAttribute | 폼 데이터 | application/x-www-form-urlencoded 형식의 폼 데이터를 객체로 바인딩. (주로 서버 사이드 렌더링에서 사용) |
자원 (Resource):
/users/123)/getUsers, /createUser/users행위 (Verb):
GET (조회), POST (생성), PUT (전체 수정), DELETE (삭제)표현 (Representation):
ResponseEntity컨트롤러 메서드는 단순히 데이터 객체만 반환할 수도 있지만, ResponseEntity 객체를 사용하면 더 정교한 응답을 만들 수 있습니다.
ResponseEntity의 장점:
200 OK (성공), 201 CREATED (생성 성공), 400 BAD_REQUEST (클라이언트 오류), 404 NOT_FOUND (자원 없음), 500 INTERNAL_SERVER_ERROR (서버 오류)@PostMapping
public ResponseEntity<User> createUser(@RequestBody UserCreateRequest request) {
User newUser = userService.create(request);
// 201 Created 상태 코드와 함께 생성된 사용자 정보를 응답
return ResponseEntity.status(HttpStatus.CREATED).body(newUser);
}
@GetMapping("/{userId}")
public ResponseEntity<User> getUser(@PathVariable Long userId) {
try {
User user = userService.findById(userId);
// 200 OK 상태 코드와 함께 사용자 정보를 응답
return ResponseEntity.ok(user);
} catch (UserNotFoundException e) {
// 사용자를 찾지 못한 경우 404 Not Found 상태 코드를 응답
return ResponseEntity.notFound().build();
}
}
@RestController는 REST API를 만들기 위한 핵심 어노테이션으로, 반환 값을 JSON 형태로 응답 본문에 직접 써줍니다.@PathVariable, @RequestParam, @RequestBody 등을 사용하여 받습니다.ResponseEntity를 사용하면, 데이터뿐만 아니라 HTTP 상태 코드와 헤더까지 포함된 풍부하고 명확한 응답을 클라이언트에게 보낼 수 있습니다.