c:forEach don't repeat same values when already present in previous row

后端 未结 3 1123
無奈伤痛
無奈伤痛 2021-01-16 20:02

I\'m having some trouble with this...

I have code like this:

Market market = new market();
List list = marketService.getMarketItemList         


        
3条回答
  •  滥情空心
    2021-01-16 20:40

    1.

    You have some errors in your HTML:

  • ${cmenu.description}/a>/li> ^ ^ | | two errors here (mising < characters) -------------------------------- replace with this ----------------------------------------------------- | | v v
  • ${cmenu.description}
  • 2.

    You should use a Map.

    The keys of the map should be the different types.

    The values should be Lists of Food objects.

    Then you can iterate over the keys of the map in your JSP.

    You'll need a nested loop to iterate over the Foods in each List.

    I think your JSP/JSTL would look something like this, but it's untested:

    
        
    typeItem Name
    ${foodMapEntry.key} | ${food.name}

    Here's some code that shows how to build the map used above:

    /* create a list of food */
    List foodList = new ArrayList();
    
    /* add some fruits to the list */
    foodList.add(new Food("Banana", "fruit"));
    foodList.add(new Food("Apple", "fruit"));
    
    /* add some veggies to the list */
    foodList.add(new Food("Onion", "vegetable"));
    foodList.add(new Food("Mushroom", "vegetable"));
    
    /* add some candy to the list */
    foodList.add(new Food("Chocolate", "candy"));
    foodList.add(new Food("Gummy Bears", "candy"));
    
    /* create a Map that maps food types to lists of Food objects */
    Map> foodMap = new HashMap>();
    
    /* populate the map */
    for (Food f : foodList) {
        String foodType = f.getType();
        if (foodMap.containsKey(foodType)) {
            foodMap.get(foodType).add(f);
        }
        else {
           List tempList = new ArrayList();
           tempList.add(f);
           foodMap.put(foodType, tempList);
        }
    }
    

    And a simple Food class:

    class Food {
       private String name;
       private String type;
    
       public Food(String n, String t) {
           name = n;
           type = t;
       }
    
       public String getName() { return name; }
       public String getType() { return type; }
    }
    

    Here's a question/answer about using Maps with JSP and JSTL.

提交回复
热议问题