Path Variables
Path Variable μ REST APIμμ URL κ²½λ‘μ ν¬ν¨λ κ°μ variable λ‘ μ¬μ©νμ¬ μ²λ¦¬νλ λ°©μμ΄λ€.
μλ₯Ό λ€μ΄,Β /users/{id} μ κ°μ URLμμΒ {id} λ Path Variable λ‘, Client κ°Β /users/123 μ μμ²νλ©΄Β 123 μ΄ parameter λ‘ μ λ¬λλ λ°©μμ΄λ€.
SpringμμλΒ @PathVariableΒ annotation μ μ¬μ©νμ¬ URL μ νΉμ λΆλΆμ method μ parameter λ‘ binding νλ€.
Path Variables - Test
public class StudentRestController {
private List<Student> theStudents;
@PostConstruct
public void loadData() {
theStudents = new ArrayList<>();
theStudents.add(new Student("Arne", "Slot"));
theStudents.add(new Student("Andy", "Robertson"));
theStudents.add(new Student("Mohamed", "Salah"));
}
@GetMapping("/students")
List<Student> getStudents() {
return theStudents;
}
@GetMapping("/student/{studentId}")
Student getStudent(@PathVariable int studentId) {
return theStudents.get(studentId);
}
}μ°μ λ§€λ² Student λ₯Ό μΆκ°ν μλ μμΌλ μ΄μ Controller λΆλΆμμ code refactoring μ μννμ.
List<Student> λ₯Ό νλ declare νκ³ @PostConstruct annotation μ μ¬μ©ν loadData() method λ₯Ό λ§λ€μ΄μ List μ νμλ€μ 미리 populate μν€λλ‘νμ.
@PostConstructλ Java Standard Annotation μΌλ‘, Spring Framework μμ μ£Όλ‘ μ¬μ©λλ©°, Spring Bean μΒ creation λ° dependency injection μ΄ μλ£λ μ΄ν,Β initialization μ μνν method μ μ μ©λ©λλ€. μ΄ annotation μ΄ λΆμ method λ Application μ΄ μμλ λΒ λ± ν λ² νΈμΆλλ©°, μ£Όλ‘ initialization logic μ define νλ λ° μ¬μ©λλ€.
λ§μ§λ§μΌλ‘, Path Variable λ‘ κ° Student object μ μ κ·Όν μ μλ getStudent() method λ₯Ό define νλ€. @PathVariable annotation μ μ¬μ©νμ¬ URL μ studentId κ°μ method μ parameter λ‘ binding νλ€.
μ΄μ http://localhost:8080/api/student/0 λ‘ GET method λ₯Ό μ¬μ©νμ¬ request λ₯Ό 보λ΄λ³΄μ.
List μ index 0 μ ν΄λΉνλ Student object κ°, JSON format μΌλ‘ return λ κ²μ λ³Ό μ μλ€.
Path Variables - Bad Test
κ·Έλ λ€λ©΄, λ§μ½ λ²μλ₯Ό λ²μ΄λλ index λ₯Ό request νλ©΄ μ΄λ»κ² λ κΉ?
status code λ 500 μΌλ‘, Internal Server Error κ° λ°μνμλ€. κ·Έλ¬λ Internal Server Error μΌ λΏ, λ΄λΆμ μΌλ‘ μ΄λ€ κ²μ μνμ¬ μ€λ₯κ° λ°μνλμ§λ μ μκ° μλ€.

console log λ₯Ό 보면 toggle μ ν¬ν¨ν΄μ μμ²λκ² κΈ΄ error log λ₯Ό νμΈν μ μλ€. μ€μν λΆλΆλ§ 보면, length κ° 3 μΈ List μ IndexOutOfBoundException μ΄ λ°μν κ²μ μ μ μλ€.