@GetMapping return 列表为空的字符串信息
@GetMapping return string info that list is empty
有时可能会发生,数据库中没有任何内容,方法 .findAll() 没有任何内容可显示,return 的主体是空的。我知道我有此函数的 return 类型 "List" 并且我不能直接 return 字符串,但是如果列表为空,我如何将响应主体作为字符串或 JSON 发送,让用户知道?我想向接收者提供数据库为空的信息,以便他清楚。
Class 注释是
@RestController
@RequestMapping(path = "/users")
代码示例:
@GetMapping
public Iterable<User> findAll() {
List<User> userList = userRepository.findAll();
if(userList.isEmpty()){
// return "This list is empty :(";
}
return userList;
}
这或多或少是你可能在前端做的事情。但是,如果需要,您可以 return 是一个包含列表和表示有关列表的消息的字符串的 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");
}
在您的控制器层中,您应该 return 一个 响应映射 与来自数据库的 returned 列表。因此,如果为空,则前端的值为零。
因此,如果 userList
的长度为空,我们就知道数据库为空,您可以向用户显示一条消息。
示例前端伪代码
fetch("${url}/users").then(response => {
if (response.data.length == 0) {
# Show message here, choose whichever way you want
alert("Oh no! Database table was empty")
}
else {
setData(response.data);
}
});
或者,您可以选择从后端抛出错误,然后在前端解决错误,并再次向用户显示有关空数据库的消息。
希望对您有所帮助。
有时可能会发生,数据库中没有任何内容,方法 .findAll() 没有任何内容可显示,return 的主体是空的。我知道我有此函数的 return 类型 "List" 并且我不能直接 return 字符串,但是如果列表为空,我如何将响应主体作为字符串或 JSON 发送,让用户知道?我想向接收者提供数据库为空的信息,以便他清楚。
Class 注释是
@RestController
@RequestMapping(path = "/users")
代码示例:
@GetMapping
public Iterable<User> findAll() {
List<User> userList = userRepository.findAll();
if(userList.isEmpty()){
// return "This list is empty :(";
}
return userList;
}
这或多或少是你可能在前端做的事情。但是,如果需要,您可以 return 是一个包含列表和表示有关列表的消息的字符串的 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");
}
在您的控制器层中,您应该 return 一个 响应映射 与来自数据库的 returned 列表。因此,如果为空,则前端的值为零。
因此,如果 userList
的长度为空,我们就知道数据库为空,您可以向用户显示一条消息。
示例前端伪代码
fetch("${url}/users").then(response => {
if (response.data.length == 0) {
# Show message here, choose whichever way you want
alert("Oh no! Database table was empty")
}
else {
setData(response.data);
}
});
或者,您可以选择从后端抛出错误,然后在前端解决错误,并再次向用户显示有关空数据库的消息。
希望对您有所帮助。