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 이 λ°œμƒν•œ 것을 μ•Œ 수 μžˆλ‹€.