基于Spring Boot的教育平台设计与实现
由于原始代码已经是一个完整的Spring Boot项目,我们可以提取其中的核心部分,例如用户信息管理模块的核心接口和实现。以下是一个简化的用户信息管理模块的代码示例:
// UserController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<User> getAllUsers() {
return userService.findAll();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable(value = "id") Long userId) {
return userService.findById(userId);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.save(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable(value = "id") Long userId, @RequestBody User userDetails) {
return userService.update(userId, userDetails);
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable(value = "id") Long userId) {
userService.deleteById(userId);
return "User with id: " + userId + " deleted successfully!";
}
}
// UserService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> findAll() {
return userRepository.findAll();
}
public User findById(Long userId) {
Optional<User> user = userRepository.findById(userId);
return user.orElse(null);
}
public User save(User user) {
return userRepository.save(user);
}
public User update(Long userId, User userDetails) {
User user = findById(userId);
if (user != null) {
// 更新用户信息
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
// ...其他属性
return save(user);
}
return null;
}
public void deleteById(Long userId) {
userRepository.deleteByI
评论已关闭