Spring/Spring REST
Spring : 기본적인 REST Controller
Korean Eagle
2020. 4. 26. 08:45
728x90
0. Rest를 구현할 때 지금까지 설정했던 의존성만 있으면 된다. 별도의 module은 필요없다.
0-1. 기본적인 구현을 위해서는 지금까지 import한 Spring Web, Spring Data Jpa, mysql 가 필요하다.
1. @Controller 대신 @RestController 사용한다.
2. @ Mapping annotation으로 바인딩 할 때 @PathVariable로 처리한다.
@GetMapping("/{id}")
public Location getLocation(@PathVariable("id") Long id) {
return this.locationRepository.findById(id).get();
}
@DeleteMapping("/{id}")
public void deleteLocation(@PathVariable("id") Long id) {
this.locationRepository.deleteById(id);
}
3. JSON객체를 받아서 사용할 때는 @RequestBody annotation 사용하여 객체로 변환한다.
@PostMapping
public Location createLocation(@RequestBody Location location) {
return this.locationRepository.save(location);
}
@PutMapping
public Location updateLocation(@RequestBody Location location) {
return this.locationRepository.save(location);
}
728x90