有时可能会发生这样的情况:数据库中什么都没有,方法 .findAll() 没有任何内容可显示并返回空主体。我知道我有这个函数的返回类型“List”,并且我不能直接返回字符串,但是如果列表为空,我如何以字符串或 JSON 形式发送响应正文以让用户知道?我想向接收者提供数据库为空的信息,这样他就清楚了。
类注释是
@RestController
@RequestMapping(path = "/users")
代码示例:
@GetMapping
public Iterable<User> findAll() {
List<User> userList = userRepository.findAll();
if(userList.isEmpty()){
// return "This list is empty :(";
}
return userList;
}
最佳答案
这或多或少是您可能在前端执行的操作。但是,如果需要,您可以返回一个 POJO,其中包含该列表和一个表示有关该列表的消息的字符串。
class UserFindAllResponse {
private final List<User> users;
private final String message;
// constructor, getters
}
@GetMapping
public UserFindAllResponse findAll() {
List<User> userList = userRepository.findAll();
return new UserFindAllResponse(userList, userList.isEmpty() ? "There appears to be no users" : "There are x users");
}
关于java - @GetMapping 返回列表为空的字符串信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61020411/