스프링부트 - @PathVariable

jeongjin-kim·2023년 9월 1일

Spring Boot

목록 보기
2/2

경로에 위치한 변수, 메서드의 매개변수의 이름이 동일한 경우

@GetMapping("/api/employees/{id}")
@ResponseBody
public String getEmployeesById(@PathVariable String id) {
    return "ID: " + id;
}

// 위와 동일
@GetMapping("/api/employees/{id}")
@ResponseBody
public String getEmployeesById(@PathVariable("id") String id) {
    return "ID: " + id;
}

경로에 위치한 변수, 메서드의 매개변수의 이름이 다른 경우

  • @PathVariable 어노테이션에 value 값을 지정해준다.
@GetMapping("/api/employeeswithvariable/{id}")
@ResponseBody
public String getEmployeesByIdWithVariableName(@PathVariable("id") String employeeId) {
    return "ID: " + employeeId;
}

@GetMapping("/api/employeeswithvariable/{id}")
@ResponseBody
public String getEmployeesByIdWithVariableName(@PathVariable(value = "id") String employeeId) {
    return "ID: " + employeeId;
}

TMI: /api/xxxx/{YYYY} 이 부분을 URI 템플릿 이라고 한다

그냥 넘어가긴 아쉬우니 내부 코드를 한번 보자

/**
 * Annotation which indicates that a method parameter should be bound to a URI template
 * variable. Supported for {@link RequestMapping} annotated handler methods.
 *
 * <p>If the method parameter is {@link java.util.Map Map&lt;String, String&gt;}
 * then the map is populated with all path variable names and values.
 *
 * @author Arjen Poutsma
 * @author Juergen Hoeller
 * @since 3.0
 * @see RequestMapping
 * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {

	/**
	 * Alias for {@link #name}.
	 */
	@AliasFor("name")
	String value() default "";

	/**
	 * The name of the path variable to bind to.
	 * @since 4.3.3
	 */
	@AliasFor("value")
	String name() default "";

	/**
	 * Whether the path variable is required.
	 * <p>Defaults to {@code true}, leading to an exception being thrown if the path
	 * variable is missing in the incoming request. Switch this to {@code false} if
	 * you prefer a {@code null} or Java 8 {@code java.util.Optional} in this case.
	 * e.g. on a {@code ModelAttribute} method which serves for different requests.
	 * @since 4.3.3
	 */
	boolean required() default true;

}

이 내용만 보고 모든 use-case 를 알 수 있을까? 싶다.

다중 경로 변수

  • uri 템플릿에 있는 변수, 메서드 매개변수 이름이 동일하면 value="" 생략
@GetMapping("/api/employees/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable String name) {
    return "ID: " + id + ", name: " + name;
}

위와 같은 다중변수를 받는 경우, 스프링부트는 편리하게도 Map<String, String> 으로 파라미터 바인딩이 가능하다.

다만, 변수 문자열에 .(dot) 이 포함된 경우 문제가 생긴다.

@GetMapping("/api/employeeswithmapvariable/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndNameWithMapVariable(@PathVariable Map<String, String> pathVarsMap) {
    String id = pathVarsMap.get("id");
    String name = pathVarsMap.get("name");
    if (id != null && name != null) {
        return "ID: " + id + ", name: " + name;
    } else {
        return "Missing Parameters";
    }
}

선택적인 경로 변수

  • requied=false 옵션을 준다.
@GetMapping(value = { "/api/employeeswithrequiredfalse", "/api/employeeswithrequiredfalse/{id}" })
@ResponseBody
public String getEmployeesByIdWithRequiredFalse(@PathVariable(required = false) String id) {
    if (id != null) {
        return "ID: " + id;
    } else {
        return "ID missing";
    }
}

다수의 경로를 받는 경우 java.util.Optional 사용


@GetMapping(value = { "/api/employeeswithoptional", "/api/employeeswithoptional/{id}" })
@ResponseBody
public String getEmployeesByIdWithOptional(@PathVariable Optional<String> id) {
    if (id.isPresent()) {
        return "ID: " + id.get();
    } else {
        return "ID missing";
    }
}
    

출처

1.https://recordsoflife.tistory.com/1034

0개의 댓글