Spring
[Spring] HTTP 요청/ 응답 관련 매핑 어노테이션
개바리여리
2025. 6. 26. 23:01
요청 매핑 어노테이션
| @RequestParam | 쿼리 파라미터, 폼 데이터에서 값을 추출 | ?name=kim&age=30 |
| @PathVariable | URL 경로 변수에서 값을 추출 | /user/{id} |
| @RequestBody | HTTP 요청 바디(JSON 등)를 자바 객체로 변환 | POST, PUT 요청에서 사용 |
| @ModelAttribute | 폼 데이터 전체를 자바 객체로 바인딩 | HTML Form 처리용 |
| @RequestHeader | HTTP 헤더 값을 가져옴 | Authorization, User-Agent 등 |
| @CookieValue | 쿠키에서 값을 추출 | JSESSIONID, 사용자 설정 쿠키 등 |
| @RequestPart | Multipart 요청에서 파일 or JSON 일부를 바인딩 | multipart/form-data 업로드 처리용 |
@GetMapping("/hello")
public String hello(@RequestParam String name // 쿼리파라미터
,@PathVariable("id") Long id
,@RequestHeader("User-Agent") String agent
,@CookieValue("token") String token
){
return "Hello World";
}
@PostMapping("/users")
public ResponseEntity<?> createUser(@RequestBody UserDto dto) {
// JSON Body를 UserDto로 바인딩
return ResponseEntity.ok().build();
}
@PostMapping("/upload")
public ResponseEntity<?> upload(
@RequestPart("file") MultipartFile file,
@RequestPart("info") UserInfoDto info
) {
// multipart 요청에서 파일 + JSON 같이 받음
return ResponseEntity.ok().build();
}
@PathVariable 같은 경우는 GET방식으로 url 이 /posts/123 이렇게 들어온다면
@GetMapping("/posts/{postId}")
public String getPost(@PathVariable("postId") Long id) {
System.out.println("조회할 게시글 ID: " + id);
return "postDetail";
}
이런식으로 받을 수 있다.
@ModelAttribute는 폼 데이터나 쿼리스트링 전체를 객체로 바인딩 해주는 역할을 한다.
html로 아래와 같이 form이 왔다고 해보자.
<form method="post" action="/register">
<input type="text" name="username">
<input type="password" name="password">
<input type="email" name="email">
<button type="submit">가입</button>
</form>
그럼 자바코드에서는 아래와 같이 받을 수 있다.
@Getter
@Setter //lombok
public class UserForm {
private String username;
private String password;
private String email;
}
@PostMapping("/register")
public String register(@ModelAttribute UserForm form) {
System.out.println("이름: " + form.getUsername());
System.out.println("이메일: " + form.getEmail());
return "result";
}
응답 매핑 어노테이션
| @ResponseBody | 메서드 반환값을 HTTP 응답 바디에 직접 씀 | 반환 객체를 JSON, XML 등으로 변환하여 내보냄 (보통 Jackson 라이브러리 사용) |
| @RestController | 컨트롤러 클래스에 붙임 | 클래스 내 모든 메서드에 @ResponseBody 자동 적용 |
| @ResponseStatus | HTTP 상태 코드를 지정 | 예: @ResponseStatus(HttpStatus.CREATED)로 201 상태 전달 |
| @JsonView | JSON 직렬화 시 출력 필드 제어 | 반환 객체의 일부 필드만 선택적으로 내보낼 때 |
| @JsonIgnore (Jackson) | 직렬화에서 특정 필드 제외 | DTO 내 특정 필드를 JSON 응답에서 제외할 때 |
1. ResponseBody
@GetMapping("/api/users/{id}")
@ResponseBody
public UserDto getUser(@PathVariable Long id) {
UserDto user = userService.findById(id);
return user; // JSON으로 직렬화되어 응답 바디에 들어감
}
2. RestController
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public UserDto getUser(@PathVariable Long id) {
return userService.findById(id);
}
}
3. ResponseStatus
@PostMapping("/api/users")
@ResponseStatus(HttpStatus.CREATED) // 201 Created 상태 코드 응답
public UserDto createUser(@RequestBody UserDto user) {
return userService.save(user);
}
4. JsonView
public class UserDto {
@JsonView(Views.Public.class)
private String username;
@JsonView(Views.Internal.class)
private String email;
}
@GetMapping("/user/public")
@JsonView(Views.Public.class)
public UserDto getPublicUser() { ... }
@GetMapping("/user/internal")
@JsonView(Views.Internal.class)
public UserDto getInternalUser() { ... }