Request 데이터를 처리하는 다양한 방법

StrayCat·2026년 2월 11일

1. URL경로 -> @PathVariable

    // GET http://localhost:8080/hello/request/star/John/age/20
    @GetMapping("/star/{name}/age/{age}")
    @ResponseBody
    public String helloRequestPath(@PathVariable String name, @PathVariable int age)
    {
        return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
    }
  • 데이터를 URL 경로로 받음
  • GetMapping으로 key/value 맵핑 필요
  • 생략 불가능 (반드시 명시)

2. Query String -> @RequestParam

    // GET http://localhost:8080/hello/request/form/param?name=John&age=20
    @GetMapping("/form/param")
    @ResponseBody
    public String helloGetRequestParam(@RequestParam(required = false) String name, int age) {
        return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
    }
  • 데이터를 Query String으로 받음
  • GetMapping에는 경로 맵핑 불필요 (? 이후 파라미터를 자동 인식 처리)
  • 생략 조건부 가능 (Primitive Type + 파라미터명 일치)

3. Body-Form -> @RequestParam

    // POST http://localhost:8080/hello/request/form/param
    // Header
    // 	Content type: application/x-www-form-urlencoded
    // Body
    // 	name=John&age=20
    @PostMapping("/form/param")
    @ResponseBody
    public String helloPostRequestParam(@RequestParam String name, @RequestParam int age) {
        return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
    }
  • 데이터를 URL이 아닌 Request Body에 담아서 전송 (Form 타입)
  • GET요청은 Body가 없으므로 POST Method 필요
  • 2와 동일하게 조건부 생략 가능

4. Body-Form -> @ModelAttribute

    // POST http://localhost:8080/hello/request/form/model
    // Header
    // 	Content type: application/x-www-form-urlencoded
    // Body
    //  name=John&age=20
    @PostMapping("/form/model")
    @ResponseBody
    public String helloRequestBodyForm(@ModelAttribute Star star) {
        return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
    }
  • 3과 동일하게 Request Body에 데이터 담아서 POST Method로 전송
  • 단 @RequestParam이 아닌 Java 클래스 객체로 (예시는 Star star) 받음
  • 클래스 객체에는 Setter 혹은 오버로딩된 생성자 필요
  • 생략 가능 (객체 타입일때 자동 적용)
// Star 객체 예시
public class Star {
    String name;
    int age;

    //오버로딩된 생성자 생성 (or @Setter)
    public Star(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

5. Query String -> @ModelAttribute 객체

    // GET http://localhost:8080/hello/request/form/param/model?name=John&age=20
    @GetMapping("/form/param/model")
    @ResponseBody
    public String helloRequestParam(@ModelAttribute Star star) {
        return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
    }
  • 4와 동일하게 @ModelAttribute 사용하지만 보내는 방식이 Form이 아닌 Query String
  • URL Query String 방식이므로 GET요청 가능 (Body 없음)
  • 동일하게 자바 객체로 받을땐 Setter 혹은 오버로딩된 생성자 필요

6. Body-Json -> @RequestBody 객체

    // POST http://localhost:8080/hello/request/form/json
    // Header
    //  Content type: application/json
    // Body
    //  {"name":"John","age":"20"}
    @PostMapping("/form/json")
    @ResponseBody
    public String helloPostRequestJson(@RequestBody Star star) {
        return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
    }
  • Front-End에서 Request로 Body에 JSON 형식의 데이터를 보낸 상황
  • @RequestBody Annotation을 명시
  • 동일하게 Java 객체에 맵핑
  • @RequestBody 생략 불가능
  • 기타 JSON을 받는 방법들
// Map으로 받기
@PostMapping("/api/users")
public User create(@RequestBody Map<String, Object> data) {
    String name = (String) data.get("name");
    int age = (Integer) data.get("age");
    // 유연하지만 타입 안전성 없음
}

// String으로 받아서 수동 파싱
@PostMapping("/api/users")
public User create(@RequestBody String jsonString) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    UserDto dto = mapper.readValue(jsonString, UserDto.class);
    // 파싱 제어 가능하지만 번거로움
}

// JsonNode사용 (Jackson)
@PostMapping("/api/users")
public User create(@RequestBody JsonNode json) {
    String name = json.get("name").asText();
    int age = json.get("age").asInt();
    // JSON 구조 탐색 가능, 동적 처리
}

// HttpServletRequest로 직접 읽기
@PostMapping("/api/users")
public User create(HttpServletRequest request) throws Exception {
    BufferedReader reader = request.getReader();
    String json = reader.lines().collect(Collectors.joining());
    // 완전한 수동 제어
}
profile
알면 좋은 것보단 잊어버리기 싫은 것들을 기록합니다.

0개의 댓글