ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스프링 웹 MVC 4일차
    Spring 2021. 3. 14. 22:28

     

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

     

    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

     

     

    1. @RequestParam 사용

    요청 url = http://localhost:8080/test?username=hello&age=20

        @ResponseBody
        @RequestMapping("/test")
        public String requestParam(
                @RequestParam("username") String memberName,
                @RequestParam("age") int memberAge) {
            log.info("username={}, age={}", memberName, memberAge);
            return "ok";
        }

    @RequestParam의 name 속성이 파라미터 이름으로 사용

    @RequestParam("username") String memberName  -->  request.getParameter("username")

     

    이때 HTTP 파라미터 이름이 변수 이름과 같으면 생략 가능

        @ResponseBody
        @RequestMapping("/test")
        public String requestParam(
                @RequestParam String username,
                @RequestParam int age) {
            log.info("username={}, age={}", username, age);
            return "ok";
        }

     

    2. @ModelAttribute 사용

     요청 url = http://localhost:8080/test?username=hello&age=20

       @ResponseBody
       @RequestMapping("/test")
        public String modelAttribute(@ModelAttribute HelloData helloData) {
            log.info("username={}, age={}", helloData.getUsername(),
                    helloData.getAge());
            return "ok";
        }
    @Data
    public class HelloData {
        private String username;
        private int age;
    }

    스프링 MVC는 @ModelAttribute가 있으면 먼저 HelloData 객체를 생성하고, 요청 파라미터 이름으로 HelloData 객체의 프로퍼티를 찾는다. 그리고 해당 프로퍼티의 setter를 호출해서 파라미터의 값으로 바인딩한다.

    따라서 helloData에는 입력값이 들어가 있는 상태이다.

     

     

     

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

     

     

    1. HttpServletRequest, HttpServletResponse 사용

        @PostMapping("/test")
        public void requestBodyString(HttpServletRequest request, HttpServletResponse response) throws IOException {
            ServletInputStream inputStream = request.getInputStream();
            String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
            log.info("messageBody={}", body);
    
            response.getWriter().write("ok");
        }

    InputStream을 통해 byte코드로 받은 후 StreamUtils를 통해 String으로 변환한다.

     

    2. HttpEntity 사용

        @PostMapping("/test")
        public HttpEntity<String> requestBodyString(HttpEntity<String> httpEntity) throws IOException {
            String body = httpEntity.getBody();
            log.info("messageBody={}", body);
    
            return new HttpEntity<>("ok");
        }

    HttpEntity를 사용하면 HTTP header와 body 정보를 편하게 조회할 수 있다.

    httpEntity.getBody로 메시지 바디 정보 조회 가능

    httpEntity.getHeaders로 헤더 정보 조회 가능

     

     

    3. @RequestBody 사용

        @ResponseBody
        @PostMapping("/test")
        public String requestBodyString(@RequestBody String body) throws IOException {
            log.info("messageBody={}", body);
            return "ok";
        }

    @RequestBody를 사용하게 되면 HTTP 메시지 바디 정보를 편리하게 조회할 수 있다. 헤더 정보가 필요하다면 HttpEntity를 사용하거나, @ReqeustHeader를 사용하면 된다.

     

     

    HTTP 요청 메시지 - JSON

     

     

    1. HttpServletRequest, HttpServletResponse 사용

        @PostMapping("/test")
        public void requestBodyJson(HttpServletRequest request, HttpServletResponse response) throws IOException {
            ServletInputStream inputStream = request.getInputStream();
            String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
            log.info("messageBody={}", body);
            HelloData helloData = objectMapper.readValue(body, HelloData.class);
            log.info("{}", helloData);
    
            response.getWriter().write("ok");
        }

    단순 텍스트와 마찬가지로 InputStream으로 JSON 데이터를 읽어올 수 있다. 하지만 텍스트와 다른 점은 JSON 데이터는 { "username": "hello", "age": 20}으로 오기 때문에 JSON 데이터를 읽을 objectMapper를 사용해서 자바 객체로 변환한다. 

     

     

    2. @RequestBody 사용

        @ResponseBody
        @PostMapping("/test")
        public String requestBodyJson(@RequestBody HelloData helloData) throws IOException {
            log.info("{}", helloData);
    
            return "ok";
        }

    @RequestBody를 사용하면 HTTP 메시지 컨버터가 HTTP 메시지 바디의 내용을 원하는 문자나 객체 등으로 변환해준다.

    HTTP 메시지 컨버터는 문자 뿐만 아니라 JSON도 객체로 변환해준다.

     

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

    'Spring' 카테고리의 다른 글

    스프링 웹 MVC 3일차  (0) 2021.03.13
    스프링 웹 MVC 2일차  (0) 2021.03.11
    스프링 웹 MVC 1일차  (0) 2021.03.09
    스프링 시큐리티 흐름 (1)  (0) 2021.03.04
    Spring boot 로 메일 보내기  (0) 2021.03.04

    댓글

Designed by Tistory.