본문 바로가기
Spring/스프링 MVC

[스프링 MVC 1편] 2 - (4) HTTP 요청 데이터

by Poorm 푸름 2023. 11. 2.

* 스프링 입문은 Window로 스프링 MVC 1편은 Mac으로 진행합니다  
 *  진도 : 섹션2 - (5) ~ (9)
 *          : 자바 클래스명,         : 코드,         : 단축키

 

1. HTTP 요청 데이터

GET - 쿼리 파라미터 메세지 바디 없이 URL의 쿼리 파라미터에 데이터 포함해 전달
POST - HTML Form 메세지 바디에 쿼리 파라미터 형식으로 전달
HTTP - Message body HTTP API에 주로 사용 (JSON, XML, TEXT)

 

2. GET - 쿼리 파라미터 

[ src - main - java - hello.servlet - basic - request - RequestParamServlet ]

<목표>

  • 전달하고 싶은 데이터: username=hello&age=20 
  • 메시지 바디 없이 URL의 쿼리 파라미터를 사용해서 데이터를 전달해보자!
  • 쿼리파라미터는URL에서 ?를 넣어 시작하고 추가파라미터는 &로 구분
    예) http://localhost:8080/request-param?username=hello&age=20

 

 

1. 파라미터 전송

- http://localhost:8080/request-param?username=hello&age=20 검색

2. 동일한 파라미터 전송
- http://localhost:8080/request-param?username=hello&age=20&username=hello2 검색

 

 

< 코드 >

- public class RequestParamServlet extends HttpServlet 

  • 서블릿을 사용하기 위해 HttpServlet을 상속받는다

- @WebServlet(name = "requestParamServlet ", urlPatterns = "/request-param" )

  • 해당 어노테이션에 경로를 입력하면 클라이언트에서 톰캣서버가 찾아서 실행한다
  • /request-param 입력하면 하위 메서드 실행
  @WebServlet(name = "requestParamServlet", urlPatterns = "/request-param")
  public class RequestParamServlet extends HttpServlet {

 

protected service (control + o)

  • servlet 호출되면 서비스 메서드도 호출
  • 위에서 만든 urlPatterns 대로 검색하면 콘솔 로그에 해당 명령어 출력
protected void service(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {

 

 

- 전체 파라미터 조회

request.getParameterNames().asIterator()
       .forEachRemaining(paramName -> System.out.println
       (paramName + "=" + request.getParameter(paramName)));
  • request.getParameter() : ("파라미터 이름")을 작성하면 값을 꺼낼 수 있다
  • asIterator() : iterator 인터페이스형으로 바꿔서 반환
  • Iterator.forEachRemaining() : Iterator의 forEachRemaining() 메서드를 사용하여 키-값 쌍을 콘솔에 출력

  • 실행 
    http://localhost:8080/request-param?username=hello&age=20
  • 실행결과
    username=hello
    age=20

 

- 단일 파라미터 조회

String username = request.getParameter( "username");
String age = request.getParameter("age");

System.out.println("username =" +username);
System.out.println("age =" +age);
  • request.getParameter() 는 한 파라미터에 하나의 값만 있을 때 사용

  • 실행
    http://localhost:8080/request-param?username=hello&age=20
  • 실행결과
    username=hello
    age=20

 

- 복수 파라미터 조회

System.out.println("이름이 같은 복수 파라미터 조회");
String[] usernames = request.getParameterValues("username");
for(String name :usernames){
    System.out.println("username = " + name);
}
  • username=hello&username=kim 과 같이 파라미터 이름은 하나인데, 값이 중복인 경우 사용
  • 중복일 때는 request.getParameterValues() 를 사용
  • (중복일 때 request.getParameter() 를 사용하면 첫 번째 값만 반환) 

  • 실행
    http://localhost:8080/request-param?username=hello&age=20&username=hello2
    실행결과

    username = helo
    username = hello2 

 

파라미터 코드
모두 조회 getParameterNames() 
단일 조회 getParameter("파라미터 key값"
복수 조회 getParameterValues("파라미터 key값")

 

 

3. HTTP 요청 데이터 - POST HTML Form 

[ src - main - webapp - basic - hello-form.html ]

<목표>

  • 메세지 바디에 전달: username=hello&age=20 
  • content-type: application/x-www-form-urlencoded
  • 주로 회원 가입상품 주문 등에서 사용하는 방식

 

-  강의에서 제공되는 html form으로 작성한 뒤 실행


1. http://localhost:8080/basic/hello-form.html 실행
2. 정적 html이 적용된 화면에서 데이터를 입력해 전송하면 콘솔로그에 찍힌다
3. http://localhost:8080/request-param 에서도 f12 누르고 form-data 확인가능


request.getParameter()는 GET URL 쿼리 파라미터 형식, POST HTML Form 형식도 둘 다 지원 가능

 

 

<참고>

  • content-type: HTTP 메시지 바디의 데이터 형식을 지정 (→ Post)
  • GET 방식은 HTTP 메시지 바디를 사용하지 않기 때문에 content-type이 없다

 

- 매번 Form 작성하기 싫다면 Postman 사용

 

  1. Postman에서 http://localhost:8080/request-param 실행
  2. body 클릭 → x-www-form-urlencoded 클릭 → 원하는 key, value 입력
  3. Headers에서 content-type이 application/x-www-form-urlencoded 로 바뀐 것 확인

 

4. HTTP Message 

[ src - main - java - hello.servlet - basic - request - RequestBodyStringServlet ]

 

- HTTP message body에 데이터를 직접 담아서 요청

- HTTP API에서 주로 사용

- JSON, XML, TEXT 중 데이터 형식은 주로 JSON 사용

 

< 단순 텍스트 형식 과정 >

 

  1. 코드 작성 후 run
  2. Postman을 이용하여 http://localhost:8080/request-body-string 
  3. Body - raw 클릭 - Text 클릭 후 보낼 메세지를 HTTP 메시지 바디에 담아서 전송
  4. content-type, 콘솔 로그 확인

< 코드 >


- public class RequestBodyStringServlet extends HttpServlet 

  • 서블릿을 사용하기 위해 HttpServlet을 상속받는다

- @WebServlet

  • 해당 어노테이션에 경로를 입력하면 클라이언트에서 톰캣서버가 찾아서 실행한다
  • /request-body-string 입력하면 하위 메서드 실행
  @WebServlet(name = "requestBodyStringServlet", urlPatterns = "/request-body-string")
  public class RequestBodyStringServlet extends HttpServlet {

 

protected service 

  • servlet 호출되면 서비스 메서드도 호출
  • 위에서 만든 urlPatterns 대로 검색하면 콘솔 로그에 해당 명령어 출력
protected void service(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {

  

- request.getInputStream (option + command + v)

  • HTTP Request로 넘어온 값들 중 일부는 getParameter()나 getParameterValues()로 읽을 수 없다
  • POST 메서드를 사용하면서 CONTENT-TYPE이 "application/json" 형식일 때 발생
  • 이를 RequestBody post data라고 한다
  • 이러한 값은 Request.getInputStream() 혹은 Request.getReader()를 통해 읽어온다
ServletInputStream inputStream = request.getInputStream();

 

 

- StreamUtils (option + command + v)

 

  • 스프링은 InputStream, OutputStream 처리를  위한 StreamUtils를 제공하고 있다
  • InputStream에 있는 내용을 String 으로 가져오는 등의 작업을 해야 하는 경우에 StreamUtils를 사용
  • StreamUtilscopyToString: 문자열로 파일을 복사함
  • copyToString: 입력 스트림을 String으로 복사함
String messageBody = StreamUtils.copyToString(inputStream,StandardCharsets.UTF_8);

 

 

- 출력

System.out.println("messageBody = " + messageBody);
response.getWriter().write("ok");

 

 

< 결과 >

 

POST http://localhost:8080/request-body-string
content-type: text/plain
message body: hello
출력 : messageBody = hello

 

 

5. HTTP Message (API) 

[ src - main - java - hello.servlet - basic - request - RequestBodyJsonServlet ]

 

< 단순 텍스트 형식 과정 >

 

  1. JSON 형식의 데이터를 객체로 바꿀 수 있도록 객체 생성
  2. 코드 작성 후 run
  3. Postman을 이용하여 http://localhost:8080/request-body-json
  4. Body - raw 클릭 - JSON 클릭 후 보낼 메세지를 HTTP 메시지 바디에 담아서 전송
  5. content-type, 콘솔 로그 확인

 

< 코드 >

 

- 객체 생성 (HelloData 클래스)

  • src - main - java - hello.servlet - basic - HelloData 클래스 생성
  • 데이터 입력 후 Getter, Setter lombok 설정


- public class RequestBodyJsonServlet extends HttpServlet 

 

- @WebServlet

  @WebServlet(name = "requestBodyJsonServlet", urlPatterns = "/request-body-json")
  public class RequestBodyJsonServlet extends HttpServlet {

 

 

protected service 

protected void service(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {

 

 

- request.getInputStream (option + command + v)

ServletInputStream inputStream = request.getInputStream();

 

 

- StreamUtils (option + command + v)

String messageBody = StreamUtils.copyToString(inputStream,StandardCharsets.UTF_8);

 

 

- 출력

System.out.println("messageBody = " + messageBody);
response.getWriter().write("ok");

 

 

---------------------   여기 까지는 4.HTTP Message 단순 텍스트 과정이랑 똑같다  ---------------------

 

 

- HelloData 변환 객체 생성

 

  • Jackson 라이브러리가 필요하다
private ObjectMapper objectMapper = new ObjectMapper(); // 선언

 

 

- message body를 HelloData 값으로 읽어오기(option + command + v)

HelloData helloData = objectMapper.readValue(messageBody,HelloData.class);

 

 

- 변환 출력

System.out.println("helloData.username = " + helloData.getUsername());
System.out.println("helloData.age = " + helloData.getAge());

 

 

< 결과 >

 

POST http://localhost:8080/request-body-json
content-type: application/json
message body: {"username": "hello", "age": 20}
출력 : messageBody = {"username": "hello", "age": 20}

콘솔 출력 : helloData.username = hello

                 helloData.age = 30

 

< 참고 >

  • JSON 파싱해서 사용할 수 있게 객체로 변환 필요 → Jackson, Gson 라이브러리
  • HTML form 도 좋지만 ( request.getParameter(...) )이 이미 편리한 파라미터 조회 기능

 

 

 

 

 

[출처] 김영한 강사님 인프런 스프링 MVC 1편

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

 

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

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

www.inflearn.com