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(id);
return new ResponseEntity<>(user, HttpStatus.OK);
}
}
// 상태 코드만
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}")
.buildAndExpand(user.getId()).toUri());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
메서드 | 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>
</dependency>
@RestController
@RequestMapping("/api/offers")
public class OfferRestController {
@Autowired
private OfferService offerService;
// 조회
@GetMapping("/{id}")
public ResponseEntity<Offer> getOffer(@PathVariable("id") int id) {
Offer offer = offerService.getById(id);
if (offer == null) {
throw new OfferNotFoundException(id);
}
return new ResponseEntity<>(offer, HttpStatus.OK);
}
// 수정
@PutMapping("/{id}")
public ResponseEntity<Offer> updateOffer(
@PathVariable("id") int id,
@RequestBody Offer offer) {
Offer current = offerService.getById(id);
if (current == null) {
throw new OfferNotFoundException(id);
}
current.setName(offer.getName());
current.setEmail(offer.getEmail());
current.setText(offer.getText());
offerService.save(current);
return new ResponseEntity<>(current, HttpStatus.OK);
}
}