@PathVariable은 스프링 MVC에서 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);
}
}
경로 변수의 이름과 메서드 파라미터의 이름이 다를 경우:
@GetMapping("/users/{userId}")
public User getUser(@PathVariable("userId") Long id) {
// 사용자 조회 로직
}
필수가 아닌 선택적 경로 변수 처리:
@GetMapping({"/users", "/users/{id}"})
public User getUser(@PathVariable(required = false) Long id) {
if (id != null) {
// 특정 사용자 조회
} else {
// 기본 사용자 또는 전체 목록 반환
}
}
@GetMapping("/users/{id:[0-9]+}")
public User getUser(@PathVariable Long id) {
// 숫자로만 구성된 id를 이용한 사용자 조회
}
@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));
}
}
required = false로 설정하지 않은 경우, 해당 경로 변수가 없으면 404 에러가 발생합니다.@PathVariable은 RESTful API 설계에서 매우 유용한 도구입니다. URL 경로를 통해 리소스를 식별하고 파라미터를 전달받을 수 있어, 깔끔하고 의미 있는 API 엔드포인트를 구성할 수 있게 해줍니다. 적절히 사용하면 직관적이고 사용하기 쉬운 API를 만들 수 있으며, 스프링의 강력한 타입 변환 기능과 결합하여 안전하고 효율적인 웹 애플리케이션을 개발할 수 있습니다.
@RequestMapping
@RequestParam
@RestController
@GetMapping
@ExceptionHandler