@RequestParam 생략 가능한 경우

백엔드&인프라 추종자·2025년 2월 24일

스프링 공부

목록 보기
11/35

@RequestParam을 사용할 때, 파라미터 타입이 int인 경우에는 생략해도 자동으로 매핑됩니다. 하지만 몇 가지 조건이 있습니다.


@RequestParam 없이도 값이 매핑되는 경우

Spring MVC는 @RequestParam을 생략해도 URL의 쿼리 파라미터 값을 메서드의 매개변수에 자동으로 바인딩할 수 있습니다.

@GetMapping("/test")
public String test(int id) {
    return "ID: " + id;
}

📌 요청 예시:

GET /test?id=10

📌 결과: "ID: 10"

이처럼 int 타입의 파라미터는 @RequestParam을 생략해도 자동 매핑됩니다.


⚠️ @RequestParam을 생략하면 주의할 점

(1) 파라미터가 없으면 400 Bad Request 발생

int기본형(primitive type) 이므로, 요청 파라미터가 없으면 null을 할당할 수 없어 예외가 발생합니다.

@GetMapping("/test")
public String test(int id) {  // id가 없으면 400 에러 발생
    return "ID: " + id;
}

📌 요청 예시 (id가 없음):

GET /test

📌 결과: 400 Bad Request (Required parameter 'id' is not present)

✅ 해결 방법: Integer(객체 타입)으로 변경

@GetMapping("/test")
public String test(Integer id) {  // id가 없어도 요청 가능 (null 허용)
    return "ID: " + (id != null ? id : "No ID");
}

📌 요청 예시 (id 없이 호출 가능):

GET /test

📌 결과: "ID: No ID"


(2) 파라미터 이름이 다르면 자동 매핑이 안됨

@GetMapping("/test")
public String test(int userId) {  // 요청 파라미터 이름이 id라면 매핑 안됨
    return "User ID: " + userId;
}

📌 요청 예시:

GET /test?id=10

📌 결과: 400 Bad Request (userId를 찾을 수 없음)

✅ 해결 방법: @RequestParam으로 매핑 명시

@GetMapping("/test")
public String test(@RequestParam("id") int userId) {
    return "User ID: " + userId;
}

📌 요청 예시:

GET /test?id=10

📌 결과: "User ID: 10"


(3) 기본값을 설정하려면 @RequestParam 필요

만약 기본값을 설정하고 싶다면 @RequestParam(defaultValue = "0")을 사용해야 합니다.

@GetMapping("/test")
public String test(@RequestParam(defaultValue = "0") int id) {
    return "ID: " + id;
}

📌 요청 예시 (id 없이 호출):

GET /test

📌 결과: "ID: 0" (기본값 적용)


✅ 결론

케이스@RequestParam 없이 가능?해결 방법
int 타입 사용가능하지만 값이 없으면 400 에러
Integer 타입 사용가능값이 없으면 null (에러 없음)
파라미터 이름이 다를 때불가능@RequestParam("id") 사용
기본값을 설정할 때불가능@RequestParam(defaultValue = "0") 사용

👉 결론적으로, @RequestParam 없이도 int 값은 받을 수 있지만, 안전하게 사용하려면 Integer 또는 @RequestParam(defaultValue = "값")을 활용하는 것이 좋습니다.

profile
AI 답변 글을 주로 올립니다.

0개의 댓글