스프링 MVC 1편 -인프런 김영한/섹션6-스프링MVC - 기본 기능

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

샐님 2023. 7. 10. 18:33
728x90
반응형

1. 클라이언트에서 서버로 요청 데어티 전달 방법 3가지 

  1) GET - 쿼리 파라미터

   - url의 쿼리 파라미터에 데이터 포함해서 전달, 검색, 필터, 페이징에서 많이 사용하는 방식

 2) POST - HTML Form

   - 메시지 바디에 쿼리 파라미터 형식으로 전달 . 회원 가입, 상품 주문, html form 사용

 3)  HTTP message body 에 데이터 담음

   - http api 에서 주로 사용, json, xml, text. 데이터 형식은 주로 json 사용. post , put, patch

 

 

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

2. 스프링으로 요청파라미터 조회 방법

 

package hello.springmvc.basic.request;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;

@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");
    }
}

 

@ResponseBody 

@ResponseBody // @RestController 와 같이 반환값은 메세지 바디에다가 넣어줌.
@RequestMapping("/request-param-v2")
public String requestParamV2(@RequestParam("username")String memberName,
                             @RequestParam("age") int memberAge){

    log.info("username={},age={}", memberName,memberAge);
    return "ok";
}

@RequestParam 사용시 파라미터 이름을 변수명과 같게 해주면 @RequestParam("") 에서 ("") 부분 생략 가능

@ResponseBody // @RestController 와 같이 반환값은 메세지 바디에다가 넣어줌.
@RequestMapping("/request-param-v2")
public String requestParamV2(@RequestParam String username,
                             @RequestParam int age){

    log.info("username={},age={}", username,age);
    return "ok";
}

요청 파라미터와 이름이 같고 String, int,Integer 등 단순 타입이면 @RequestParam 도 생략가능.

@ResponseBody // @RestController 와 같이 반환값은 메세지 바디에다가 넣어줌.
@RequestMapping("/request-param-v2")
public String requestParamV2(String username,
                              int age){

    log.info("username={},age={}", username,age);
    return "ok";
}

파라미터 필수 여부 - requestParamRequired

 

@ResponseBody // @RestController 와 같이 반환값은 메세지 바디에다가 넣어줌.
@RequestMapping("/request-param-required")
public String requestParamRequired(@RequestParam(required = true) String username,
                                   @RequestParam(required = false) int age){

    log.info("username={},age={}", username,age);
    return "ok";
}

 필수 파라미터 (username) 없이 api 요청한 경우

    - 400 에러, Bad Request 를 반환한다.

 기본형(primitive)에 null 입력 /request-param 요청 @RequestParam(required = false) int age null

을 int 에 입력하는 것은 불가능(500 예외 발생) 따라서 null 을 받을 수 있는 Integer 로 변경하거나, 또는 다음에 나오는 defaultValue 사용

 

defaultValue 

@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";
}

Map

@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";
}

 

728x90
반응형