Spring.Boot Moustache如何在模型中导航Java Map

问题描述 投票:0回答:1

我有一个地图,其中包含关键产品代码和相应的产品名称。我希望能够使用地图使用产品密钥查找和显示产品名称。我不知道如何在胡须中表现出来。我将地图存储在Spring MVC应用程序的Model对象中。它确实必须是地图,但是地图似乎是进行查找的最自然的方法。我不知道我还能用另一个方便的结构来表示这一点。我已经显示了我的表格摘要。如何显示地图?可能吗“ 002022”->“香蕉”将是一个示例。

       @GetMapping("/products/display")
       public String displayProductsByCode(Model model){

         Map<String,String> m = repo.findProductsByCode();
         model.addAttribute("productLookup",m);
         return "productDisplay";
     }

   <table>
     <tr>
       <thead>
       <th> Product Code></th>
       <th> Product Name </th>
      </thead>
    </tr>
    {{# ????}}
     <tr>
     <td> ..I want the product code here</td>
     </tr>
    {{/ ???? }} 
   </table>
java spring-boot mustache
1个回答
0
投票

创建一个用于保存产品代码和产品名称并将其显示在视图中的类。

public class Product {
    private String code;
    private String name;


    public Product() {

    }

    public Product(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

在您的控制器中创建此产品类型的列表。如何实现如何获得所有产品取决于您。这是示例:

@GetMapping("/product/display")
    public String displayProductByCode(Map<String, Object> model){
     //your logic here to retrieve products. Below simple example:
     List<Product> listForModel = new ArrayList<>();
     Product product1 = new Product("002022", "Banana");
     Product product2 = new Product("003033", "Mango");
     listForModel.add(product1);
     listForModel.add(product2);
     model.put("productsById", listForModel);
     return "index";

}

这是index.html文件。

 <table cellspacing="10px">
        <tr>
            <th>Product Code</th>
            <th>Product Name</th>
        </tr>

        {{#productsById}}           
        <tr>
            <td>{{code}}</td>
            <td>{{name}}</td>
        </tr>
      {{/productsById}}
    </table>
© www.soinside.com 2019 - 2024. All rights reserved.