본문 바로가기
스프링

스프링 - HTTP 파라미터 처리 방식

by 개발자 포비 2024. 12. 6.

스프링 MVC는 웹 애플리케이션 개발에서 HTTP 요청을 처리하는 다양하고 유연한 방법을 제공합니다. 특히 HTTP 요청 파라미터를 처리하는 방식은 개발자가 자주 마주하는 중요한 부분인데, 상황과 요구사항에 맞게 적절한 방식을 선택할 수 있습니다. 요청 파라미터를 처리하는 주요 방식들을 실제 HTTP 요청 예시와 함께 살펴보겠습니다.

1. @RequestParam 사용

GET /hello?name=kim&age=20
@GetMapping("/hello")
public String hello(@RequestParam("name") String name,
                   @RequestParam("age") int age) {
    return "hello " + name; // "hello kim" 반환
}

2. @ModelAttribute 사용

POST /save
Content-Type: application/x-www-form-urlencoded

name=kim&age=20
@Data
public class UserForm {
    private String name;
    private int age;
}

@PostMapping("/save")
public String save(@ModelAttribute UserForm form) {
    // form.getName() == "kim"
    // form.getAge() == 20
    return "save";
}

3. HttpServletRequest 직접 사용

GET /hello?name=kim
@GetMapping("/hello")
public String hello(HttpServletRequest request) {
    String name = request.getParameter("name"); // "kim"
    return "hello " + name;
}

4. @PathVariable 사용

GET /users/123
@GetMapping("/users/{userId}")
public String user(@PathVariable("userId") String userId) {
    return "user " + userId; // "user 123" 반환
}

5. Map으로 받기

POST /users
Content-Type: application/x-www-form-urlencoded

name=kim&age=20&role=admin
@PostMapping("/users")
public String users(@RequestParam Map<String, Object> paramMap) {
    String name = (String) paramMap.get("name");     // "kim"
    String age = (String) paramMap.get("age");       // "20"
    String role = (String) paramMap.get("role");     // "admin"
    return "success";
}

6. @RequestBody를 사용한 JSON 처리

POST /api/users
Content-Type: application/json

{
    "name": "kim",
    "age": 20,
    "role": "admin"
}
@PostMapping("/api/users")
public String createUser(@RequestBody UserForm userForm) {
    // userForm.getName() == "kim"
    // userForm.getAge() == 20
    return "success";
}

이런 다양한 방식들 중에서 API의 특성과 처리해야 할 데이터의 형태에 따라 적절한 방식을 선택하면 됩니다. 각 방식의 특징을 잘 이해하고 상황에 맞게 활용하는 것이 중요합니다.

댓글