@RestController
public class HelloWorldController {
//GET
// /hello-world (endpoint)
@GetMapping("/hello-world")
public String helloWorld(){
return "Hello Wolrd";
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class HelloWorldBean {
private String message;
}
// HelloWorldController class
@GetMapping("/hello-world-bean")
public HelloWorldBean helloWorldBean(){
return new HelloWorldBean("Hello World");
}
@GetMapping("/hello-world-bean/path-variable/{name}")
public HelloWorldBean helloWorldBean(@PathVariable String name) {
return new HelloWorldBean(String.format("Hello World, %s", name));
}
Get /hello-world-bean/path-variable/{변수}
@Data
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private Date joinDate;
}
@Service
public class UserDaoService {
private static List<User> users = new ArrayList<>();
private static int usersCount = 3;
static {
users.add(new User(1, "Kenneth", new Date()));
users.add(new User(2, "Alice", new Date()));
users.add(new User(3, "Elena", new Date()));
}
public List<User> findAll() {
return users;
}
public User save(User user) {
if (user.getId() == null) {
user.setId(++usersCount);
}
users.add(user);
return user;
}
public User findOne(int id) {
for (User user : users) {
if (user.getId() == id) return user;
}
return null;
}
}
@RestController
public class UserController {
private UserDaoService service;
public UserController(UserDaoService service){
this.service = service;
}
@GetMapping("/users")
public List<User> retrieveAllUsers() {
return service.findAll();
}
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id) {
User user = service.findOne(id);
return user;
}
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user){
User savedUser = service.save(user);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedUser.getId())
.toUri();
return ResponseEntity.created(location).build();
}
}
Get /users/[존재하지 않는 ID]
//UserController class
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id) {
User user = service.findOne(id);
// HTTP Status Code 제어 -> Exception Handling
if(user == null) {
throw new UserNotFoundException(String.format("ID[%s] not found", id));
}
return user;
}
//UserNotFoundException class
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
// HTTP Status code
// 2xx -> Ok
// 4xx -> Client 오류
// 5xx -> Server 오류
@ResponseStatus(HttpStatus.NOT_FOUND) // 404 -> 사용자가 요청한 리소스 찾지 못함
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExceptionResponse {
private Date timestamp;
private String message;
private String details;
}
-CustomizeReponseEntityExceptionHandler 클래스: 모든 예외상황을 handling
@RestController
@ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
// UserNotFoundException Handler
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
}
}