본문 바로가기
Spring Tutorial

[스프링MVC 기본 기능 4] HTTP 요청 파라미터 (GET, POST)

by 미소5 2023. 8. 21.

클라이언트에서 서버로 요청 데이터를 전달할 때는 주로 다음 3가지 방법을 사용한다.

[스프링 MVC 10] 서블릿: HTTP 요청 데이터 (*중요) (tistory.com)

 

[스프링 MVC 10] 서블릿: HTTP 요청 데이터 (*중요)

HTTP 요청 데이터를 어떻게 조회하는지 알아보자! HTTP 요청 메시지를 통해 클라이언트에서 서버로 데이터를 전달하는 방법 (3가지) 1. GET - 쿼리 파라미터 /url?username=hello&age=20 메시지 바디 없이, URL

joly156.tistory.com

 

스프링 MVC에서는 훨씬 깔끔하고 효율적으로 HTTP 요청 데이터를 조회할 수 있는데, 스프링으로 요청 파라미터를 조회하는 방법을 단계적으로 알아보자.


HttpServletRequest의 request.getParameter() 를 사용하면 다음 두가지 요청 파라미터를 조회할 수 있다.

  • GET - 쿼리 파라미터 전송
    • 예시) http://localhost:8080/request-param?username=hello&age=20
  • POST - HTML Form 전송

 

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


  • 단순히 HttpServletRequest가 제공하는 방식(request.getParameter)으로 요청 파라미터를 조회
@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");
    }

    ...

  • main/resources/static/basic/hello-form.html
    • Post Form 페이지 생성 (테스트용 HTML Form)
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</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>

 


GET 실행


POST 실행

 


 

[스프링 MVC 11] 서블릿: HTTP 요청 데이터 - GET 쿼리 파라미터 (tistory.com)

 

[스프링 MVC 11] 서블릿: HTTP 요청 데이터 - GET 쿼리 파라미터

다음 데이터를 클라이언트에서 서버로 전송해보자. username=hello age=20 GET방식(메시지 바디 없이, URL의 쿼리 파라미터를 사용)으로 전송해보자. 쿼리 파라미터는 URL에 다음과 같이 ? 를 시작으로 보

joly156.tistory.com

 

728x90
반응형