컨트롤러에서 URL 요청을 처리할 때 쿼리스트링을 통해 값을 전달할 수 있는데,
이때, 파라미터 값을 필수 값이 아닌 선택적으로 전달해야 하는 경우에
스프링(부트 and 레거시) @RequestParam 어노테이션에서
(required = false) 명시하여 필수 값이 아니게 지정할 수 있다.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class exampleController {
// Spring Boot (스프링 부트) 예시
@GetMapping("/test")
public String handleSpringBootRequest(
@RequestParam(required = false) String param1,
@RequestParam(required = false) Integer param2) {
String response = "param1 : " + param1 + ", param2 : " + param2;
return response;
}
// Spring Legacy (스프링 레거시) 예시
@GetMapping("/test")
public String handleSpringLegacyRequest(
@RequestParam(value = "param1", required = false) String param1,
@RequestParam(value = "param2", required = false) Integer param2) {
String response = "param1 : " + param1 + ", param2 : " + param2;
return response;
}
}
/* 예시 요청 URL */
// http://localhost:8080/test - 파라미터 없이 호출
// http://localhost:8080/test?param1=value - param1만
// http://localhost:8080/test?param2=17 - param2만
// http://localhost:8080/test?param1=value¶m2=42 - 두 파라미터 모두 포함
//--------------------------------------------------------------------------
'Spring' 카테고리의 다른 글
Spring Boot 스프링 부트 dev tools 개발 생산성 향상을 위한 개발 도구 설정, 애플리케이션 자동 재시작, 브라우저 자동 새로고침 (0) | 2023.06.04 |
---|---|
SpringBoot 스프링부트 @Scheduled 스케줄링 / 정해진 시각, 반복적으로 메서드 실행 (0) | 2023.02.19 |
Spring MVC패턴 실행순서 / 구조 (0) | 2022.05.01 |
Spring 스프링 (Legacy) 환경설정 [MVC] (0) | 2022.02.20 |
최근댓글