본문 바로가기

spring

HTTP 요청 파라미터

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

GET 쿼리 파리미터 전송 방식이든, POST HTML Form 전송 방식이든 둘다 형식이 같으므로 구분없이 조회할 수 있다. 이것을 간단히 요청 파라미터(request parameter) 조회라 한다.


@Slf4j
@Controller
public class RequestParamController {
    @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");
    }
}

http://localhost:8080/request-param-v1?username=kim&age=20

 

request.getParameter()

여기서는 단순히 HttpServletRequest가 제공하는 방식으로 요청 파라미터를 조회했다.

 

이제 POST 방식으로 전달하는 폼을 만들어보자

<!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>

해당 html파일은 WEB-INF밑이 아니라 static아래에 만들어 주었다.

http://localhost:8080/basic/hello-form.html

 

첫번째 쿼리파라미터를 이용한 GET방식도 두번째 폼을 사용한 POST방식도 모두 같은 기능의 컨트롤러로 수행이 가능하다.

'spring' 카테고리의 다른 글

@ModelAttribute  (0) 2023.03.31
@RequestParam  (0) 2023.03.30
HTTP 요청 - 기본, header 조회  (0) 2023.03.30
요청 매핑 - 연습  (0) 2023.03.27
요청 매핑  (0) 2023.03.27