Everyday Dev System

스프링에서 클라이언트가 서버에 값을 전달하는 방식 본문

내배캠 주요 학습/Spring 입문

스프링에서 클라이언트가 서버에 값을 전달하는 방식

chaeyoung- 2023. 6. 13. 12:52

- pathVariable 빼고 RequestParam, ModelAttribute는 어노테이션 생략 가능.

  스프링에서 원시타입일 경우에는 @RequestParam가 생략, 그 외에 클래스 타입같은 경우에는 @ModelAttribute이 생략되어 있다고 자동으로 인식하고 실행시킴.

 

1. Path Variable 방식

- @PathVariable (required= false) 기재 가능. (값 여부에 따른 오류 발생 핸들링 가능)

서버에 보내려는 하는 데이터를 URL 경로에 추가를 할 수 있습니다.

 

1) 필요한 부분의 데이터인 name에 {name}으로 중괄호를 씌어서 mapping url에 기재

2) @PathVariable 라는 어노테이션을 매개 변수 앞에 기재

 

    // [Request sample]
    // GET http://localhost:8080/hello/request/star/Robbie/age/95
    @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("/star/{name}/age/{age}")
    @ResponseBody
    public String helloRequestPath(@PathVariable String nme, @PathVariable int age)
    {
        return String.format("Hello, @PathVariable.<br> name = %s, age = %d", nme, age);
    }

 

 

2. RequestParam 방식 

- @RequestParam 생략 가능.

- @RequestParam(required= false) 를 통해 해당 키에 따른 값이 전달이 안되어도 오류가 나지 않도록 설정 가능

더보기
    @PostMapping("/form/param")
    @ResponseBody
    public String helloPostRequestParam(@RequestParam(required = false) String name, @RequestParam int age) {
        return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
    }

@RequestParam(required= false) 를 입력하면 클라이언트로 부터 전달받은 값 중 해당 값이 포함되어 있지 않아도 오류가 발생하지 않는다는 의미. 대신 값은 null이 됨.

 

1) GET

    // [Request sample]
    // GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95
    @GetMapping("/form/param")
    @ResponseBody
    public String helloGetRequestParam(@RequestParam String name, @RequestParam int age) {
        return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
    }

GET http://localhost:8080/hello/request/form/param?name=Robbie&age=95

- ? 는 쿼리String 방식 시작함을 의미

- &로 데이터 구분함.

 

2) POST

    // [Request sample]
    // POST http://localhost:8080/hello/request/form/param
    // Header
    //  Content type: application/x-www-form-urlencoded
    // Body
    //  name=Robbie&age=95
    @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);
    }

 

 

3. @ModelAttribute 

- 받아올 객체 내에 Setter() 혹은 오버로딩된 생성자가 반드시 필요함.

- @ModelAttribute는 생략이 가능하다.

1) Post

package com.sparta.springmvc.request;
import lombok.Getter;

@Getter
public class Star {
    String name;
    int age;

    public Star(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
    @PostMapping("/form/model")
    @ResponseBody
    public String helloRequestBodyForm(@ModelAttribute Star star) {
        return String.format("Hello, @ModelAttribute.<br> (name = %s, age = %d) ", star.name, star.age);
    }

쿼리스트링 방식의 데이터를 객체에 매핑해서 가져올 수 있습니다.

스프링 내부에서 자동으로 객체 만들어 줍니다.

 

 

2) Get

    // [Request sample]
    // GET http://localhost:8080/hello/request/form/param/model?name=Robbie&age=95
    @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. Body에 json 형태로 넘어올 경우.

    // [Request sample]
    // POST http://localhost:8080/hello/request/form/json
    // Header
    //  Content type: application/json
    // Body
    //  {"name":"Robbie","age":"95"}
    @PostMapping("/form/json")
    @ResponseBody
    public String helloPostRequestJson(@RequestBody Star star) {
        return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
    }

HTTP Body 부분에 json 형식으로 데이터가 넘어왔을 때에는 @RequestBody를 매개변수 앞에 기재해야 합니다.