<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.4.RELEASE</version> </dependency> @Controller @RequestMapping("/users") public class UserController { @GetMapping("/{id}") public ResponseEntity<User> getUserById(@PathVariable int id) { User user = userService.getUserById(id); if (user != null) { return ResponseEntity.ok(user); } else { return ResponseEntity.notFound().build(); } } @PostMapping public ResponseEntity<User> createUser(@RequestBody User user) { User newUser = userService.createUser(user); return ResponseEntity.created(URI.create("/users/" + newUser.getId())).body(newUser); } @PutMapping("/{id}") public ResponseEntity<User> updateUser(@PathVariable int id, @RequestBody User user) { User updatedUser = userService.updateUser(id, user); if (updatedUser != null) { return ResponseEntity.ok(updatedUser); } else { return ResponseEntity.notFound().build(); } } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteUser(@PathVariable int id) { boolean result = userService.deleteUser(id); if (result) { return ResponseEntity.noContent().build(); } else { return ResponseEntity.notFound().build(); } } } @Service public class UserService { public User getUserById(int id) { } public User createUser(User user) { } public User updateUser(int id, User user) { } public boolean deleteUser(int id) { } }


上一篇:
下一篇:
切换中文