728x90
Spring request param
@ResponseBody
public String requestParamRequired(@RequestParam(required = true) String username,
@RequestParam(required = false) Integer age) {
log.info("username={}, age={}", username, age);
return "ok";
}
http://localhost:8080/request-param-required?username=hello
→ age가 없을 때 파라미터를 int age로 하면 500 에러 → int 형은 primitive type이어서 null값을 가질 수 없음
Integer
로 바꿔주면 age는 null
이 됨 (아니면 defaultValue 지정)
username=hello, age=null
username의 required=true
http://localhost:8080/request-param-required?username=
라고 요청을 보내면 username = “” (빈 문자열)이 됨
빈 문자열은 null이 아니기 때문에 에러 발생x
username=, age=null
defaultValue
null이 아닌 빈 문자열이 들어와도 설정한 기본값이 적용
@RequestMapping("/request-param-default")
@ResponseBody
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";
}
728x90
'BackEnd > Spring' 카테고리의 다른 글
[Spring/JPA] @Version을 통한 낙관적 락(Optimistic Lock) (1) | 2023.06.10 |
---|---|
[Spring] Kotlin + Spring boot 프로젝트에 Redis 적용 (1) | 2023.03.14 |
[Spring] 로깅 logging (0) | 2022.12.12 |
[Spring] 스프링 MyBatis 연동 (0) | 2022.11.01 |
[Spring] 스프링 - File Upload, Download (0) | 2022.11.01 |