본문 바로가기
Back-end/Spring Boot

[SpringBoot 에러] Required request parameter 'id' for method parameter type String is not present

by whatamigonnabe 2022. 6. 28.

문제발생 원인은?

아래처럼 @RequestParam 어노테이션을 사용하여 '명시적으로 쿼리 필드 이름을 지정해서 가져오는 경우',

클라이언트에서 해당 쿼리 필드를 요청하지 않거나 오타 등으로 다른 이름으로 요청하게되면 발생하는 오류입니다.

@RestController
@RequestMapping("/api/server")
public class HelloController {

    @GetMapping("/hello")
    public User hello(@RequestParam String id, @RequestParam String email, @RequestParam String phoneNumber) {
        User user = new User();
        user.setId(id);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        return user;
    }
}

해결방법은?

1. DTO 객체를 매개 변수로 받기

아래와 같이 DTO클래스를 만들어서 매개 변수로 받게 되면, 클라이언트가 요청하지 않은 쿼리 필드에 대해서 null /  0 등 디폴트값으로 처리 되면서 에러가 발생하지 않습니다.

@GetMapping("/hello")
public User hello(User user) {
    return user;
}

 

 2.@RequestParam 어노테이션에 (Required = false)를 추가하기

아래처럼 어노테이션에 속성을 추가하면 필드값이 없는 것에 대하여 무시하게 됩니다.

@GetMapping("/hello")
public User hello(@RequestParam(required = false) String id, @RequestParam String email, @RequestParam String phoneNumber) {