상세 컨텐츠

본문 제목

Spring MVC @RequestParam

프레임워크/Spring Boot

by 최승호 2022. 5. 23. 12:00

본문

 

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

@RequestParam 어노테이션은

컨트롤러에서 서블릿 요청 메소드(쿼리 파라미터 혹은 폼 데이터) 파라미터를 메소드 매개변수로 바인딩 할 수 있다.

문자열 데이터 받기

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

파라미터 이름을 지정하지 않고 Map으로 받기

// 문자열 데이터 받기(파라미터 미지정)
@GetMapping("/paramtestMap")
public void paramtestMap(@RequestParam Map<String, String> paramMap) {
	log.info("paramMap : {}", paramMap);
}

@RequestParam 어노테이션 생략

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

 

관련글 더보기

댓글 영역