簡體   English   中英

model.addAttribute() 對於每個循環

[英]model.addAttribute() For Each Loop

我剛剛開始涉足 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>

在此處輸入圖片說明

有什么建議? 提前感謝任何幫助!

原來我不需要為控制器中的每個循環運行一個。 我刪除了循環並使用 addAttribute 方法將 test.getBody() 插入模型中,它運行良好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM