@PathVariable

코딩냥이·2024년 9월 10일

Annotation

목록 보기
21/34

@PathVariable

@PathVariable은 스프링 MVC에서 URL 경로의 일부를 파라미터로 받아올 때 사용하는 어노테이션입니다.

기능

  • URL 경로에 포함된 변수 값을 메서드의 파라미터로 받아옵니다.
  • RESTful API에서 리소스를 식별하는 데 주로 사용됩니다.
  • 동적인 URL 처리를 가능하게 합니다.

사용 방법

기본적인 사용 방법은 다음과 같습니다:

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
        // id를 이용한 사용자 조회 로직
        return userService.findById(id);
    }
}

주요 특징

  1. 타입 변환: 문자열로 들어온 URL 경로 변수를 자동으로 지정된 타입으로 변환합니다.
  2. 필수 값: 기본적으로 필수 값으로 처리되며, 값이 없으면 404 에러가 발생합니다.
  3. 다중 변수: 여러 개의 경로 변수를 동시에 사용할 수 있습니다.
  4. 정규식 지원: URL 템플릿에서 정규식을 사용하여 경로 변수를 제한할 수 있습니다.

고급 사용법

1. 변수명 명시

경로 변수의 이름과 메서드 파라미터의 이름이 다를 경우:

@GetMapping("/users/{userId}")
public User getUser(@PathVariable("userId") Long id) {
    // 사용자 조회 로직
}

2. 선택적 경로 변수

필수가 아닌 선택적 경로 변수 처리:

@GetMapping({"/users", "/users/{id}"})
public User getUser(@PathVariable(required = false) Long id) {
    if (id != null) {
        // 특정 사용자 조회
    } else {
        // 기본 사용자 또는 전체 목록 반환
    }
}

3. 정규식을 이용한 경로 변수 제한

@GetMapping("/users/{id:[0-9]+}")
public User getUser(@PathVariable Long id) {
    // 숫자로만 구성된 id를 이용한 사용자 조회
}

4. 다중 경로 변수

@GetMapping("/users/{userId}/posts/{postId}")
public Post getUserPost(@PathVariable Long userId, @PathVariable Long postId) {
    // 특정 사용자의 특정 게시물 조회
}

예외 처리

경로 변수 값이 예상한 형식이 아닐 경우 MethodArgumentTypeMismatchException이 발생할 수 있습니다. 이를 전역적으로 처리하려면:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<String> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
        String name = ex.getName();
        String type = ex.getRequiredType().getSimpleName();
        Object value = ex.getValue();
        String message = String.format("'%s' should be a valid '%s' and '%s' isn't", 
                                        name, type, value);
        
        return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST);
    }
}

테스트

@PathVariable이 적용된 컨트롤러 메서드를 테스트할 때:

@WebMvcTest(UserController.class)
class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testGetUser() throws Exception {
        mockMvc.perform(get("/users/1"))
               .andExpect(status().isOk())
               .andExpect(jsonPath("$.id").value(1));
    }
}

주의사항

  1. 타입 불일치: 경로 변수의 값이 지정된 타입으로 변환될 수 없는 경우 예외가 발생합니다.
  2. 필수 값 처리: required = false로 설정하지 않은 경우, 해당 경로 변수가 없으면 404 에러가 발생합니다.
  3. 보안: 경로 변수를 통해 받은 값에 대해 적절한 검증과 이스케이프 처리가 필요할 수 있습니다.

베스트 프랙티스

  1. 명확한 네이밍: 경로 변수 이름을 명확하고 의미 있게 지정하세요.
  2. 타입 안전성: 가능한 한 구체적인 타입을 사용하여 자동 형변환의 이점을 활용하세요.
  3. 유효성 검사: 필요한 경우 받아온 값에 대해 추가적인 유효성 검사를 수행하세요.
  4. 문서화: API 문서에 경로 변수의 의미와 제약사항을 명확히 기술하세요.

결론

@PathVariable은 RESTful API 설계에서 매우 유용한 도구입니다. URL 경로를 통해 리소스를 식별하고 파라미터를 전달받을 수 있어, 깔끔하고 의미 있는 API 엔드포인트를 구성할 수 있게 해줍니다. 적절히 사용하면 직관적이고 사용하기 쉬운 API를 만들 수 있으며, 스프링의 강력한 타입 변환 기능과 결합하여 안전하고 효율적인 웹 애플리케이션을 개발할 수 있습니다.

연관 포스팅

@RequestMapping
@RequestParam
@RestController
@GetMapping
@ExceptionHandler

profile
HelloMeow~!

0개의 댓글