【问题标题】:@GetMapping return string info that list is empty@GetMapping 返回列表为空的字符串信息
【发布时间】:2020-04-03 21:06:58
【问题描述】:

有时可能会发生,在数据库中什么都没有,方法 .findAll() 没有可显示的内容并返回空主体。我知道我有这个函数“列表”的返回类型,我不能直接返回字符串,但是如果列表为空,我如何发送响应正文作为字符串或 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;
}

【问题讨论】:

    标签: java rest controller response


    【解决方案1】:

    这或多或少是你可能在前端做的事情。但是,如果需要,您可以返回一个 POJO,其中包含 List 和表示有关 List 的消息的 String。

    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");
    }
    

    【讨论】:

      【解决方案2】:

      在您的控制器层中,您应该返回一个响应映射,其中包含来自数据库的返回列表。因此,如果为空,则前端的值为零。

      所以如果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);
          }
      });
      

      或者,您可以选择从后端抛出错误,然后在前端解决错误,然后再次向用户显示有关空数据库的消息。

      希望对你有帮助。

      【讨论】:

      • 虽然这个解决方案是基于前端的,但它是非常有帮助的答案。非常感谢!顺便说一句“哦,不!”抓住了我:)
      猜你喜欢
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 2021-10-17
      • 2014-12-30
      • 2020-09-05
      • 1970-01-01
      相关资源
      最近更新 更多