https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestparam
Web on Servlet Stack
Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, “Spring Web MVC,” comes from the name of its source module (spring-webmvc), but it is more com
docs.spring.io
컨트롤러에서 서블릿 요청 메소드(쿼리 파라미터 혹은 폼 데이터) 파라미터를 메소드 매개변수로 바인딩 할 수 있다.
@RestController
public class RequestParamTestController {
// 문자열 데이터 받기
@GetMapping("/paramtest")
public void paramtest(@RequestParam String id, @RequestParam String name) {
log.info("id : {}", id);
log.info("name : {}", name);
}
}
@RequestParam의 기본 설정은 required = true 속성이며 false로 변경하거나 java.util.Optional 래퍼로 인수를 선언하여 사용할 수 있다.
만약 required 속성이 true인 상태에서 매개변수를 모두(id, name) 넘겨주지 않으면 다음과 같이 예외가 발생한다.
Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'name' for method parameter type String is not present]
// 문자열 데이터 받기(파라미터 일부 누락)
@GetMapping("/paramtestNull")
public void paramtestNull(@RequestParam Optional<String> id, @RequestParam(required = false) String name) {
log.info("id : {}", id);
log.info("name : {}", name);
}
// 문자열 데이터 받기(파라미터 미지정)
@GetMapping("/paramtestMap")
public void paramtestMap(@RequestParam Map<String, String> paramMap) {
log.info("paramMap : {}", paramMap);
}
@RequestParam 어노테이션 사용 선택사항이다. 기본적인 데이터 타입(primitive, primitive wrapper, enum, String, Locale, Class 등)은 생략하고 받을 수 있다.
// 데이터 받기(어노테이션 미지정)
@GetMapping("/paramtestNoAnno")
public void paramtestNoAnno(String id, String name) {
log.info("id : {}", id);
log.info("name : {}", name);
}

| Spring MVC @CookieValue (0) | 2022.05.24 |
|---|---|
| Spring MVC @RequestMapping - 요청받기 (0) | 2022.05.19 |
| Spring Boot 신규 프로젝트 생성(Spring Initializer 활용) (0) | 2022.05.17 |
댓글 영역