복습

스프링 MVC 기본 기능 - HTTP 요청 데이터 조회 본문

Spring뿌시기/6주차 - 스프링 MVC 1편

스프링 MVC 기본 기능 - HTTP 요청 데이터 조회

ykm1256 2022. 11. 14. 14:36

HTTP 요청 데이터 조회

  • 클라이언트에서 서버로 요청 데이터를 전달할 때는 주로 다음 3가지 방법을 사용한다.
  • GET - 쿼리 파라미터
    • /url?username=hello&age=20
    • 메시지 바디 없이, URL의 쿼리 파라미터에 데이터를 포함하여 전달
    • 예) 검색, 필터, 페이징 등에서 많이 사용하는 방식
  • POST - HTML Form
    • content-type : application/x-www-form-urlencoded
    • 메시지 바디에 쿼리 파라미터 형식으로 전달 username=hello&age=20
    • 예) 회원 가입, 상품 주문, HTML Form 사용
  • HTTP message body에 데이터를 직접 담아서 요청
    • HTTP API에서 주로 사용, JSON, XML, TEXT
    • 데이터 형식은 주로 JSON 사용
    • POST, PUT, PATCH에서 사용

요청 파라미터 - 쿼리 파라미터, HTML Form

  • HttpServletRequest 객체의 request.getParameter()를 사용하면 두가지 요청 파라미터를 조회할 수 있다.
  • GET - 쿼리 파라미터 전송
    • http://localhost:8080/request-param?username=hello&age=20
  • POST - HTML Form 전송
POST /request-param ...
content-type: application/x-www-form-urlencoded
username=hello&age=20
  • 두가지 방식 모두 형식이 같으므로 구분없이 조회할 수 있다.
  • 이를 요청 파라미터 조회라 한다.

RequestParamController

@Slf4j
@Controller
public class RequestParamController {

/**
* 반환 타입이 없으면서 이렇게 응답에 값을 직접 집어넣으면, view 조회X
*/

    @RequestMapping("/request-param-v1")
    public void requestParamV1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        int age = Integer.parseInt(request.getParameter("age"));
        log.info("username={}, age={}", username, age);
        
        response.getWriter().write("ok");
    }
}
  • 단순히 request.getParameter()를 통해 요청 파라미터를 조회했다.
  • 이렇게 반환 타입이 없고, response에 값을 직접 집어 넣으면 view가 조회되지 않는다.

Post Form 페이지 생성

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/request-param-v1" method="post">
        username: <input type="text" name="username" />
        age: <input type="text" name="age" />
        <button type="submit">전송</button>
    </form>
</body>
</html>
  • 리소스는 /resource/static 아래에 두면 스프링 부트가 자동으로 인식한다.
  • Jar를 사용하면 webapp 경로를 사용할 수 없다. 이제부터 정적 리소스도 클래스 경로에 함께 포함해야 한다.

HTTP 요청 파라미터 - @RequestParam

  • @RequestParam을 사용하면 요청 파라미터를 매우 편리하게 사용할 수 있다.

requestParamV2

@ResponseBody
@RequestMapping("/request-param-v2")
public String requestParamV2(
    @RequestParam("username") String memberName,
    @RequestParam("age") int memberAge) {
    
    log.info("username={}, age={}", memberName, memberAge);
    return "ok";
}
  • @RequestParam : 파라미터 이름으로 바인딩
  • @ResponseBody : View 조회를 무시하고 HTTP message body에 직접 해당 내용 입력

requestParamV3

@ResponseBody
@RequestMapping("/request-param-v3")
public String requestParamV3(
        @RequestParam String username,
        @RequestParam int age) {

    log.info("username={}, age={}", username, age);
    return "ok";
}
  • HTTP 파라미터 이름이 변수 이름과 같으면 @RequestParam의 name 속성 생략 가능

requestParamV4

@ResponseBody
@RequestMapping("/request-param-v4")
public String requestParamV4(String username, int age) {
    log.info("username={}, age={}", username, age);
    return "ok";
}
  • String, int, Integer 등의 단순 타입이면 @RequestParam도 생략 가능하다.
  • 애노테이션을 생략하면 스프링 MVC는 내부에서 required=false를 적용한다.

파라미터 필수 여부 - requestParamRequired

@ResponseBody
@RequestMapping("/request-param-required")
public String requestParamRequired(
        @RequestParam(required = true) String username,
        @RequestParam(required = false) Integer age) {
        
    log.info("username={}, age={}", username, age);
    return "ok";
}
  • @RequestParam.required
    • 파라미터 필수 여부
    • 기본값은 true이다.
  • /request-param으로 요청하면 username이 없으므로 400 예외가 발생한다.
  • /request-param?username= 으로 요청 시 빈문자로 인식하여 통과된다.
  • 기본형(primitive)에 null 입력
    • /request-param 요청 시 age는 required=false이므로 null인데
    • int형은 null을 받을 수 없으므로 500예외가 발생한다.
    • 따라서 Integer로 변경하거나, defaultValue를 사용한다.

기본값 적용 - requestParamDefault

@ResponseBody
@RequestMapping("/request-param-default")
public String requestParamDefault(
        @RequestParam(required = true, defaultValue = "guest") String username,
        @RequestParam(required = false, defaultValue = "-1") int age) {
        
    log.info("username={}, age={}", username, age);
    return "ok";
}
  • 파라미터에 값이 없는 경우 defaultValue로 설정한 기본값이 적용된다.
  • 이미 기본값이 설정되어 있어서 required는 의미가 없게 된다.
  • defaultValue는 빈 문자가 입력되어도 설정한 기본값이 적용된다.

파라미터를 Map으로 조회하기 - requestParamMap

@ResponseBody
@RequestMapping("/request-param-map")
public String requestParamMap(@RequestParam Map<String, Object> paramMap) {

    log.info("username={}, age={}", paramMap.get("username"),
    paramMap.get("age"));
    return "ok";
}
  • 파라미터를 Map, MultiValueMap으로 조회할 수 있다.
  • 파라미터의 값이 1개가 확실하다면 Map을 사용하면 되지만, 그렇지 않다면 MultiValueMap을 사용하자.

HTTP 요청 파라미터 - @ModelAttribute

  • 실제 개발을 하면 요청 파라미터를 받아서 필요한 객체를 만들고 그 객체에 값을 넣어주어야 한다.
@RequestParam String username;
@RequestParam int age;

HelloData data = new HelloData();
data.setUsername(username);
data.setAge(age);
  • 보통 이렇게 코드를 작성하는데, 스프링은 @ModelAttribute를 통해 이 과정을 자동화해준다.

HelloData

@Data
public class HelloData {
    private String username;
    private int age;
}
  • 롬복의 @Data를 사용하면 @Getter , @Setter , @ToString , @EqualsAndHashCode , @RequiredArgsConstructor 를 자동으로 적용해준다.

@ModelAttribute 적용 - modelAttributeV1

@ResponseBody
@RequestMapping("/model-attribute-v1")
public String modelAttributeV1(@ModelAttribute HelloData helloData) {

    log.info("username={}, age={}", helloData.getUsername(), helloData.getAge());
    return "ok";
}
  • @ModelAttribute를 사용하면 자동으로 HelloData 객체가 생성되고, 파라미터의 값도 모두 들어가 있다.
  • @ModelAttribute 실행 과정
    • HelloData 객체 생성
    • 파라미터 이름으로 HelloData 객체의 프로퍼티를 찾는다.
    • 프로퍼티의 setter를 호출하여 파라미터의 값을 입력(바인딩)한다.
    • 예) 파라미터 이름이 username이면 setUsername() 메서드를 찾아 호출하면서 값을 입력한다.

프로퍼티란

  • 객체에 getUsername(), setUsername() 메서드가 있으면, 이 객체는 username이라는 프로퍼티를 가지고 있다.
  • username 프로퍼티의 값을 변경하면 setUsername()이 호출되고, 조회하면 getUsername()이 호출된다.

바인딩 오류

  • 만약 age=abc 처럼 타입이 맞지 않는 데이터가 들어오면 BindException이 발생한다.
  • 이는 검증부분에서 처리할 수 있다.

@ModelAttribute 생략 - modelAttributeV2

@ResponseBody
@RequestMapping("/model-attribute-v2")
public String modelAttributeV2(HelloData helloData) {

    log.info("username={}, age={}", helloData.getUsername(),
    helloData.getAge());
    return "ok";
}
  • @ModelAttribute는 생략할 수 있다.
  • 앞의 @RequestParam도 생략할 수 있어서 혼란이 발생할 수 있다.
  • 따라서 스프링은 생략 시 다음과 같은 규칙을 적용한다.
    • String, int, Integer 같은 단순 타입은 @RequestParam
    • 나머지는 @ModelAttribute(argument resolver로 지정해둔 타입 외)

HTTP 요청 메시지 - 단순 텍스트

  • 요청 파라미터와 다르게 HTTP 메시지 바디를 통해 데이터가 직접 넘어오는 경우는 @RequestParam, @ModelAttribute를 사용할 수 없다.
  • HTTP 메시지 바디의 데이터는 InputStream을 사용해서 직접 읽을 수 있다.

RequestBodyStringController

@Slf4j
@Controller
public class RequestBodyStringController {

    @PostMapping("/request-body-string-v1")
    public void requestBodyString(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        
        log.info("messageBody={}", messageBody);
        response.getWriter().write("ok");
    }
}
  • Postman으로 POST 타입으로 데이터를 보내확인하면 로그가 잘 찍히는 것을 확인할 수 있다.

Input, Output 스트림, Reader - requestBodyStringV2

@PostMapping("/request-body-string-v2")
public void requestBodyStringV2(InputStream inputStream, Writer responseWriter)
throws IOException {
    String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
    log.info("messageBody={}", messageBody);
    responseWriter.write("ok");
}
  • InputStream(Reader) : HTTP 요청 메시지 바디의 내용을 직접 조회
  • OutputStream(Writer) : HTTP 응답 메시지의 바디에 직접 결과 출력

HttpEntity - requestBodyStringV3

@PostMapping("/request-body-string-v3")
public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) {
    String messageBody = httpEntity.getBody();
    log.info("messageBody={}", messageBody);
    
    return new HttpEntity<>("ok");
}
  • HttpEntity
    • HTTP header, body 정보를 편리하게 조회
    • 메시지 바디 정보를 직접 조회
    • 요청 파라미터를 조회하는 기능(@RequestParam, @ModelAttribute)과 관계 없음
  • HttpEntity는 응답에도 사용 가능
    • 메시지 바디 정보 직접 반환
    • 헤더정보 포함 가능
    • view 조회 X
  • HttpEntity를 상속받은 다음 객체들도 같은 기능을 제공한다.
  • RequestEntity
    • HttpMethod, url 정보가 추가, 요청에서 사용
  • ResponseEntity
    • HTTP 상태 코드 설정 가능, 응답에서 사용
    • return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED)
스프링 MVC 내부에서 HTTP 메시지 바디를 읽어서 문자나 객체로 변환해서 전달해주는데,
HTTP 메시지 컨버터(HttpMessageConverter)라는 기능을 사용한다.

@RequestBody - requestBodyStringV4

@ResponseBody
@PostMapping("/request-body-string-v4")
public String requestBodyStringV4(@RequestBody String messageBody) {
    log.info("messageBody={}", messageBody);
    return "ok";
}
  • @RequestBody를 사용하면 바디 정보를 편리하게 조회할 수 있다.
  • 참고로 헤더 정보가 필요하면 HttpEntity나 @RequestHeader를 사용하면 된다.
  • 마찬가지로 이는 요청 파라미터를 조회하는 @RequestParam, @ModelAttribute와 전혀 관계가 없다.

@ReponseBody

  • @ResponseBody를 사용하면 응답 결과를 HTTP 메시지 바디에 직접 담아서 전달할 수 있다.
  • 물론 이경우에도 view를 사용하지 않는다.

HTTP 요청 메시지 - JSON

@Slf4j
@Controller
public class RequestBodyJsonController {
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @PostMapping("/request-body-json-v1")
    public void requestBodyJsonV1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        
        log.info("messageBody={}", messageBody);
        HelloData data = objectMapper.readValue(messageBody, HelloData.class);
        log.info("username={}, age={}", data.getUsername(), data.getAge());
        
        response.getWriter().write("ok");
    }
}
  • HttpServletRequest를 사용해서 직접 HTTP 메시지 바디에서 데이터를 읽어와 문자로 변환한다.
  • JSON 데이터를 String 타입으로 변경했으므로 objectMapper를 사용하여 자바 객체로 변환하여 사용한다.

requestBodyJsonV2 - @RequestBody 문자 변환

@ResponseBody
@PostMapping("/request-body-json-v2")
public String requestBodyJsonV2(@RequestBody String messageBody) throws IOException {
    HelloData data = objectMapper.readValue(messageBody, HelloData.class);
    log.info("username={}, age={}", data.getUsername(), data.getAge());
    return "ok";
}
  • 이전에 학습했던 @RequestBody를 사용하여 HTTP 메시지에서 데이터를 꺼내고 messageBody에 저장한다.
  • 문자로 된 JSON 데이터인 messageBody를 objectMapper를 통해서 자바 객체로 변환한다.
  • 문자로 변환하고 json으로 변환하는 과정이 불편한데 한번에 객체로 변환할 수는 없을까?

requestBodyJsonV3 - @RequestBody 객체 변환

@ResponseBody
@PostMapping("/request-body-json-v3")
public String requestBodyJsonV3(@RequestBody HelloData data) {
    log.info("username={}, age={}", data.getUsername(), data.getAge());
    return "ok";
}
  • @RequestBody 파라미터를 통해 직접 만든 객체를 지정할 수 있다.
  • HttpMessageConverter가 JSON 데이터를 우리가 지정한 HelloData로 변환해주어 바로 사용할 수 있다.
  • 여기서는 @RequestBody를 생략할 수 없다.
    • 생략 시 String, int, Integer와 같은 단순 타입을 제외한 모든 타입은 @ModelAttribute로 적용되어 버린다.
    • 따라서 HTTP 메시지 바디가 아니라 요청 파라미터를 처리하게 된다.
HTTP 요청 시에 content-type이 application/json인지 꼭 확인해야 한다.
그래야 JSON을 처리할 수 있는 HTTP 메시지 컨버터가 실행된다.

 

requestBodyJsonV4 - HttpEntity

@ResponseBody
@PostMapping("/request-body-json-v4")
public String requestBodyJsonV4(HttpEntity<HelloData> httpEntity) {
    HelloData data = httpEntity.getBody();
    log.info("username={}, age={}", data.getUsername(), data.getAge());
    return "ok";
}
  • 앞에서 사용했던 HttpEntity를 사용해도 된다.

requestBodyJsonV5

@ResponseBody
@PostMapping("/request-body-json-v5")
public HelloData requestBodyJsonV5(@RequestBody HelloData data) {
    log.info("username={}, age={}", data.getUsername(), data.getAge());
    return data;
}
  • @ResponseBody를 사용하면 반환타입을 데이터 객체로 하여 반환할 수 있다.
  • 이때도 HTTP 메시지 컨버터를 통해 JSON으로 응답이 된다.
  • 마찬가지로 HttpEntity도 사용가능 하다.
  • @RequestBody 요청
    • JSON 요청 -> HTTP 메시지 컨버터 -> 객체
  • @ResponseBody 응답
    • 객체 -> HTTP 메시지 컨버터 -> JSON 응답

 


출처

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1

 

스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 - 인프런 | 강의

웹 애플리케이션을 개발할 때 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. 스프링 MVC의 핵심 원리와 구조를 이해하고, 더 깊이있는 백엔드 개발자로 성장할 수 있습니다., -

www.inflearn.com