Restful Web Service with Spring

Controller + 뷰 템플릿@RestController, @RequestBody, ResponseEntity, @PathVariable 등을 사용하여 REST API 구현@Controller
@RequestMapping("/api")
public class RestApiController {
@Autowired
private UserService userService;
@GetMapping("/users")
@ResponseBody
public List<User> listAllUsers() {
return userService.getAllUsers();
}
}@Controller + @ResponseBody 조합의 축약형@ResponseBody를 생략 가능@RestController
@RequestMapping("/api")
public class RestApiController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> listAllUsers() {
return userService.getAllUsers();
}
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
User user = userService.getById
// 상태 코드만
new ResponseEntity<>(HttpStatus.NO_CONTENT);
// 본문 + 상태
new ResponseEntity<>(bodyObject, HttpStatus.OK);
// 본문 + 헤더 + 상태
new ResponseEntity<>(bodyObject, headers, HttpStatus.CREATED);@PostMapping("/users")
public ResponseEntity<Void> createUser(
@RequestBody User user,
UriComponentsBuilder ucBuilder) {
userService.save(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(
ucBuilder.path("/api/users/{id}
| 메서드 | URI | 설명 |
|---|---|---|
| GET | /api/users | 전체 조회 |
| GET | /api/users/1 | 단건 조회 |
| POST | /api/users | 생성 |
| PUT | /api/users/3 | 수정 |
| DELETE | /api/users/4 | 삭제 |
| DELETE | /api/users | 전체 삭제 |
<!-- Jackson Databind: JSON↔객체 자동 변환 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.16.2</version>
</dependency>
<!-- Spring Web 포함 (DispatcherServlet, Tomcat 포함) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
@RestController
@RequestMapping("/api/offers")
public class OfferRestController {
@Autowired
private OfferService offerService;
// 조회
@GetMapping("/{id}")
public ResponseEntity<Offer> getOffer(@PathVariable("id"