[REST][Spring] @RequestParam, @ModelAttribute, @RequestBody 사용법 정리
2023. 1. 24. 14:20
컨트롤러에서 HTTP req 받을 때, HTTP method에 따라 query parameter (GET) 혹은 HTTP request message body (POST PUT PATCH)로 데이터가 넘어올 수 있다.
각 상황에서 컨트롤러는 @RequestParam, @ModelAttribute, @RequestBody를 각각 어떻게 사용해서 데이터를 받아야 하는지 정리
1. Query parameter
주로 거의 GET 요청 받을 때 (HTTP GET은 request body X; query parameter로만 데이터 전달 - )
요렇게 GET 요청 보낼꺼임, 이름 혹은 age (혹은 두 조건 모두) 사용해서 학생 검색
// client-side
const fetch = async (params?: StudentParams): Promise<Student[]> => {
const response = await axios.get<Student[]>(URL, {
params, // requestBody (data)가 아니라 params를 넘겨줌!
})
return response?.data || []
}
export interface StudentParams {
name?: string
age?: number
}
1-1. @RequestParam
모두 받던가 일부만 받기 가능
// back-end
@GetMapping
public List<Student> getAll(
@RequestParam(required = false) String name,
@RequestParam(required = false) int age
) {...}
// query parameter에 있던거 다 명시
@GetMapping("class/{id}")
public List<ProductAttribute> getByClass(
@PathVariable(name="id") String classId,
@RequestParam(required = false) String name // query parameter에 있던거 '일부만'
) {...}
1-2. @ModelAttribute
// back-end
@GetMapping
public List<Student> getAll(@ModelAttribute StudentParam params) {...}
// 바로 Java 객체로 mapping 가능
public List<Student> getAll(StudentParam params) {...}
// 보통은 생략함; 생략했는데 객체로 mapping해야 한다면 자동으로 @ModelAttribute 붙음
Postman으로 GET 쿼리 날렸을 때 컨트롤러에서 어떻게 받는지
// 아무것도 안 넘기면 객체는 null로 채워짐 ⭐
client : GET http://localhost:8080/students
controller : studentParams = StudentParams(name=null, age=null)
// 넘긴 것 (name)만 채워지고 나머진 null ⭐
client : GET http://localhost:8080/students?name=kim
controller : studentParams = StudentParams(name=kim, age=null)
client : GET http://localhost:8080/students?name=kim&age=19
controller : studentParams = StudentParams(name=kim, age=19)
// 보너스) list 넘기기 가능 (classParams는 그냥 내가 즉석에서 생각한 객체)
client : GET http://localhost:8080/class?studentIds=1,2,3,4
controller : classParams = ClassParams(classId=null, studentIds=[1, 2, 3, 4])
2. HTTP request message body
POST, PUT, PATCH에서 활용,
req message body에 넣어준 값 (주로 JSON)을 @RequestBody로 받음
⭐ 객체 field에 매칭되는 값이 body에 없으면, 해당 객체 필드는 null로 채워짐 (ModelAttribute랑 비슷)
const save = async (studentDTO: StudentDTO): Promise<Student> => {
const response = await axios.post<Student>(
URL,
studentDTO
)
return response?.data
}
@PostMapping
public Student save(
@RequestBody StudentRequestDTO requestBody
// 보내준 형태랑 받는 형태랑 일치해야 함 (⭐ 일치 안되는 필드는 null로 채움)
) {...}
'<BE> > [Spring Framework]' 카테고리의 다른 글
[REST][Spring] @ModelAttribute에 @setter 필요 vs @Requestbody엔 필요X (0) | 2023.01.24 |
---|---|
[REST][Spring] GET → @RequestBody 대신 @RequestParam/ @ModelAttribute (0) | 2023.01.24 |