1. 개요

이 빠른 사용방법(예제)에서는 Spring의 @PathVariable 어노테이션을 살펴 보겠습니다 .

간단히 말해, @PathVariable 어노테이션은 요청 URI의 매핑 템플릿 변수를 처리하는 데 사용할 수 있습니다 , 및 방법의 매개 변수로 사용합니다.

@PathVariable 및 다양한 속성 을 사용하는 방법을 살펴 보겠습니다 .

2. 간단한 매핑

@PathVariable 어노테이션 의 간단한 사용 사례 는 기본 키로 엔터티를 식별하는 끝점입니다.

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

이 예에서는 @PathVariable 어노테이션을 사용 하여 변수 {id}로 표시되는 URI의 템플릿 부분을 추출합니다 .

간단한 GET 요청/ API / 직원 / {ID} 호출합니다 getEmployeesById를 추출 된 ID 값 :

http://localhost:8080/api/employees/111 
---- 
ID: 111

이제이 어노테이션을 자세히 살펴보고 해당 속성을 살펴 보겠습니다.

3. 경로 변수 이름 지정

이전 예에서는 method 매개 변수와 경로 변수의 이름이 동일하기 때문에 템플릿 경로 변수의 이름 정의를 건너 뛰었습니다.

그러나 경로 변수 이름이 다른 경우 @PathVariable 어노테이션 의 인수에 지정할 수 있습니다 .

@GetMapping("/api/employeeswithvariable/{id}")
@ResponseBody
public String getEmployeesByIdWithVariableName(@PathVariable("id") String employeeId) {
    return "ID: " + employeeId;
}
http://localhost:8080/api/employeeswithvariable/1 
---- 
ID: 1

명확성을 위해 경로 변수 이름 PathVariable ( "id")  대신 @PathVariable (value = "id") 로 정의 할 수도 있습니다 .

4. 단일 요청의 다중 경로 변수

사용 사례에 따라 여러 메서드 매개 변수가있는 컨트롤러 메서드에 대한 요청 URI에 둘 이상의 경로 변수가있을 수 있습니다 .

@GetMapping("/api/employees/{id}/{name}")
@ResponseBody
public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable String name) {
    return "ID: " + id + ", name: " + name;
}
http://localhost:8080/api/employees/1/bar 
---- 
ID: 1, name: bar

java.util.Map <String, String> 유형의 메소드 매개 변수를 사용하여 둘 이상의 @PathVariable 매개 변수를 처리 할 수도 있습니다 .

@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";
    }
}
http://localhost:8080/api/employees/1/bar 
---- 
ID: 1, name: bar

그러나 경로 변수 문자열에 점 (.) 문자가 포함 된 경우 여러 @ PathVariable 매개 변수 를 처리하는 동안 약간의 문제 가 있습니다. 여기 에서 이러한 코너 사례에 대해 자세히 설명 했습니다 .

5. 선택적 경로 변수

Spring에서는 기본적 으로 @PathVariable 어노테이션이 달린 메소드 매개 변수 가 필요합니다.

@GetMapping(value = { "/api/employeeswithrequired", "/api/employeeswithrequired/{id}" })
@ResponseBody
public String getEmployeesByIdWithRequired(@PathVariable String id) {
    return "ID: " + id;
}

모양에 따라 위의 컨트롤러는 / api / employeeswithrequired/ api / employeeswithrequired / 1 요청 경로를 모두 처리해야 합니다. 그러나 @PathVariables어노테이션 처리 된 메서드 매개 변수 는 기본적으로 필수이므로 필수 경로 / api / employees전송 된 요청을 처리하지 않습니다 .

http://localhost:8080/api/employeeswithrequired 
---- 
{"timestamp":"2020-07-08T02:20:07.349+00:00","status":404,"error":"Not Found","message":"","path":"/api/employeeswithrequired"} 

http://localhost:8080/api/employeeswithrequired/1 
---- 
ID: 111

우리는 이것을 두 가지 방법으로 처리 할 수 ​​있습니다.

5.1. @PathVariable 을 필요하지 않음으로 설정

@PathVariable필수 속성 false 로 설정하여 선택 사항으로 만들 수 있습니다. 따라서 이전 예제를 수정하여 이제 경로 변수를 사용하거나 사용하지 않고 URI 버전을 처리 할 수 ​​있습니다.

@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";
    }
}
http://localhost:8080/api/employeeswithrequiredfalse 
---- 
ID missing

5.2. java.util.Optional 사용

Spring 4.1부터 java.util.Optional <T> (Java 8 이상에서 사용 가능)을 사용하여 필수가 아닌 경로 변수를 처리 할 수도 있습니다 .

@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";
    }
}

이제 요청에 경로 변수 ID지정하지 않으면 기본 응답을받습니다.

http://localhost:8080/api/employeeswithoptional 
----
ID missing 

5.3. Map <String, String> 유형의 메소드 매개 변수 사용

앞서 살펴본 것처럼 java.util.Map 유형의 단일 메소드 매개 변수를 사용하여 요청 URI의 모든 경로 변수를 처리 할 수 있습니다 . 이 전략을 사용하여 선택적 경로 변수 케이스를 처리 할 수도 있습니다.

@GetMapping(value = { "/api/employeeswithmap/{id}", "/api/employeeswithmap" })
@ResponseBody
public String getEmployeesByIdWithMap(@PathVariable Map<String, String> pathVarsMap) {
    String id = pathVarsMap.get("id");
    if (id != null) {
        return "ID: " + id;
    } else {
        return "ID missing";
    }
}

6. @PathVariable의 기본값

기본적으로 @PathVariable 어노테이션이 달린 메서드 매개 변수에 대한 기본값을 정의 할 수있는 규정이 없습니다 . 그러나 위에서 설명한 것과 동일한 전략을 사용하여 @PathVariable 의 기본값 사례를 충족 할 수 있습니다 . 경로 변수 에서 null 만 확인 하면됩니다.

예를 들어 java.util.Optional <String, String> 을 사용하여 경로 변수가 null 인지 여부를 식별 할 수 있습니다 . 이 경우 는 null 우리는 단지 기본 값으로 요청에 응답 할 수 있습니다 :

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

7. 결론

이 기사에서는 Spring의 @PathVariable 어노테이션 을 사용하는 방법에 대해 논의했습니다 . 또한 선택적 매개 변수 및 기본값 처리와 같은 다양한 사용 사례에 맞게 @PathVariable 어노테이션 을 효과적으로 사용하는 다양한 방법을 식별했습니다 .

이 기사에 표시된 코드 예제는 Github 에서도 사용할 수 있습니다 .