Replies: 1 comment
-
✅ 1. Controller 정의 및 설정
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/hello")
public String hello() {
return "Hello, REST";
}
}✅ 2. HTTP 요청 메서드 매핑
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.save(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.delete(id);
}
}✅ 3. 요청 데이터 바인딩
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}@GetMapping("/search")
public List<User> searchUsers(@RequestParam String name) {
return userService.findByName(name);
}@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.save(user);
}@PostMapping("/form")
public String submitForm(@ModelAttribute UserForm form) {
return "ok";
}✅ 4. 응답 및 예외 처리
@DeleteMapping("/users/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
userService.delete(id);
}@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class ApiController {
@GetMapping("/public")
public String publicApi() {
return "CORS 허용됨";
}
}@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleNotFound(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
🤨
Beta Was this translation helpful? Give feedback.
All reactions