基于 Spring Boot 和 Vue 开发前后端分离快速开发平台源码分享
// 假设有一个User实体类和对应的UserController
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
// 获取所有用户
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userService.findAll();
return ResponseEntity.ok(users);
}
// 根据ID获取用户
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable(value = "id") Long userId) {
User user = userService.findById(userId);
return ResponseEntity.ok(user);
}
// 创建新用户
@PostMapping
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
User newUser = userService.save(user);
return ResponseEntity.ok(newUser);
}
// 更新用户信息
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable(value = "id") Long userId, @Valid @RequestBody User userDetails) {
User user = userService.findById(userId);
if (user != null) {
user.setName(userDetails.getName());
// ...其他字段更新
User updatedUser = userService.save(user);
return ResponseEntity.ok(updatedUser);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
// 删除用户
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteUser(@PathVariable(value = "id") Long userId) {
User user = userService.findById(userId);
if (user != null) {
userService.deleteById(userId);
return ResponseEntity.ok().build();
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
这个简单的UserController展示了如何使用Spring Boot创建REST API来对User实体进行基本的CRUD操作。这个例子旨在教育开发者如何设计RESTful API和与之交互的服务层代码。
评论已关闭