For access to the HTTP request body. Body content is converted to the declared method argument type by using HttpMessageConverter implementations.
전송할 데이터가 많을 경우 데이터를 폼에 담에 전송할 때 사용한다.
폼에 담긴 변수명과 RequestBody에 담긴 멤버필드명이 일치하지 않는 경우, RequestBody에 담긴 멤버필드는 null로 초기화된다.
ex) 로그인할 때 id, password를 폼으로 묶어서 요청할 때 사용한다.
@Data
class SignInRequest {
private String id;
private String password;
}
@Slf4j
@RestController
public class TestController {
@PostMapping("/sign-in")
@ResponseStatus(HttpStatus.OK)
public void signIn(
@RequestBody SignInRequest signInRequest
) {
log.info("id: " + signInRequest.getId());
log.info("password: " + signInRequest.getPassword());
/* 로그인하는 로직 */
}
}
For access to URI template variables.
요청 경로에 변수명을 추가하고 싶을 때 사용한다.
경로에 적힌 변수 타입과 Controller에서 받는 파라미터 변수명, 타입과 일치해야 한다.
ex) 공지사항 목록을 불러올 때 2페이지를 불러오는 경우
-> URL 경로: {{baseURL}}/boards/{page}
-> 요청 경로: {{baseURL}}/boards/2
@Slf4j
@RestController
public class TestController {
@GetMapping("/boards/{page}")
@ResponseStatus(HttpStatus.OK)
public void getBoards(
@PathVariable int page
) {
log.info("page: " + page);
/* 2페이지를 불러오는 로직 */
}
}
For access to the Servlet request parameters, including multipart files. Parameter values are converted to the declared method argument type.
요청 URL에 데이터 정보(Multipart file을 포함한 데이터)를 추가하고 싶을 때 사용한다.
요청 URL 끝에 ?를 통해 name=value 형식으로 데이터를 추가를 하고 여러 개를 추가할 경우 &를 통해 데이터를 추가한다.
@RequestParam에서 name, value, defaultValue, required 옵션을 통해 기본 설정을 할 수 있다.
ex) 공지사항 목록을 불러올 때 2페이지에서 'happy'라는 문자열이 포함된 공지사항을 10개 불러오는 경우
-> URL 경로: {{baseURL}}/boards/{page}
-> 요청 경로: {{baseURL}}/boards/2?pageSize=10&title=happy
@Slf4j
@RestController
public class TestController {
@GetMapping("/boards/{page}")
@ResponseStatus(HttpStatus.OK)
public void getBoards(
@PathVariable int page,
@RequestParam int pageSize,
@RequestParam String title
) {
log.info("page: " + page);
log.info("pageSize: " + pageSize);
log.info("title: " + title);
/* title이 포함된 공지사항을 2페이지, pageSize만큼 불러오는 로직 */
}
}
For access to an existing attribute in the model (instantiated if not present) with data binding and validation applied.
@Data
public class QuestionCreateRequest {
private int projectNo;
private String title;
private String content;
private List<MultipartFile> files;
}
@Slf4j
@RestController
public class TestController {
@PostMapping("/v1/api/question")
@ResponseStatus(HttpStatus.CREATED)
public void createQuestion(
@UserInfo AuthenticatedUser user,
@ModelAttribute QuestionCreateRequest questionCreateRequest
) {
qnaService.createQuestion(user.getUserId(), questionCreateRequest);
}
}
참고자료:
https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-multipart