【问题标题】:model.addAttribute() For Each Loopmodel.addAttribute() 对于每个循环
【发布时间】:2020-05-11 01:22:46
【问题描述】:

我刚刚开始涉足 Spring MVC。我正在使用外部加密货币 API。我正在尝试使用 for each 循环来迭代 JSON 响应,以使用 addAttribute 方法将每个值插入到模型中。不过,我只得到最后一个值。

控制器:

    @RequestMapping(value = "/Tables", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    public String test(Model model) throws IOException {
        ResponseEntity<coins[]> test = getRequest();
        for (coins i : test.getBody()) {
            model.addAttribute("coins", i);
        }
        return "Tables";
    }

    public ResponseEntity<coins[]> getRequest() throws IOException {
        RestTemplate restTemplate = new RestTemplate();
        String apiUrl = "https://api.coingecko.com/api/v3/coins/list";
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(new MediaType[]{MediaType.APPLICATION_JSON}));
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        ResponseEntity<coins[]> response = restTemplate.exchange(apiUrl, HttpMethod.GET, entity, coins[].class);
        if (response.getStatusCode() == HttpStatus.OK) {
            return response;
        } else {
            System.out.println("Error");
        }

        return response;
    }

型号:

    @JsonProperty("id")
    public String id;
    @JsonProperty("symbol")
    public String symbol;
    @JsonProperty("name")
    public String name;

查看:

<tr th:each="coins : ${coins}">
     <td th:text="${coins.id}"></td>
     <td th:text="${coins.symbol}"></td>
     <td th:text="${coins.name}"></td>
     <td class="text-right">
          <a href="javascript:void(0)" class="btn btn-link btn-info btn-icon btn-sm like"><i class="tim-icons icon-heart-2"></i></a>
          <a href="javascript:void(0)" class="btn btn-link btn-danger btn-icon btn-sm remove"><i class="tim-icons icon-simple-remove"></i></a>
     </td>
</tr>

enter image description here

有什么建议吗?提前感谢任何帮助!

【问题讨论】:

    标签: java json spring-boot spring-mvc thymeleaf


    【解决方案1】:

    原来我不需要在控制器中为每个循环运行一个。我删除了循环并使用 addAttribute 方法将 test.getBody() 插入模型中,它工作正常。

    【讨论】:

      猜你喜欢
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多