【问题标题】:Spring creating collection in viewSpring 在视图中创建集合
【发布时间】:2014-05-27 19:54:11
【问题描述】:

假设我们的视图获得了数据库中所有“Ingrediënt”的列表,我们现在想要将 Quantity 信息添加到每个 Ingrediënt。

逻辑:

成分数量:

  • 成分:成分
  • 数量:数量

数量:

  • 字符串:单位
  • int : 数量

成分:

  • 字符串:名称

菜式:

  • 集合:成分
  • 字符串:名称

问题:

我们如何将每个选定成分的输入组合到成分数量列表中。我们只希望我们的列表包含选定的成分。

笔记。 Quantity 有一个 String unit 和一个 Int quantity 字段

额外的。 我正在考虑使用自定义转换器,但不知道如何去做。

【问题讨论】:

  • Ingrediënt 是否有 IngredientQuantity 字段?请分享您现在拥有的任何 JSP sn-p。
  • 还没有什么,还在思考阶段:)
  • 哈哈哈...你不需要转换器。 Ingrediënt 有 IngredientQuantity 字段吗?

标签: java spring spring-mvc view converter


【解决方案1】:

您不需要Converter。 Converter 用于高级类型转换,例如将传入的字符串 'yyyy-mm-dd zone' 转换为 java.util.Date,反之亦然。

Spring 提供 JSTL tags library 将 modelAttribute 附加到 <form> 及其字段。

您还可以在<form> 中附加一个成分数量列表,<form> 中有很多关于如何使用列表的教程。

一个这样的例子是here

更新:

在您的情况下,您将在控制器设置方法中将 Dish 和一个空的成分数量列表添加到模型中,如下所示

class IngredientFormModel{

   //It is important to use AutoPopulatingList as your list is dynamic 
   AutoPopulatingList<IngredientQuantity> ingredientQuantityList = new AutoPopulatingList<IngredientQuantity>(IngredientQuantity.class);   
}

@RequestMapping(method=RequestMethod.GET)
public String setupForm(Model model) {      
    model.addAttribute("dish", dish);

    IngredientFormModel ingredientFormModel = new IngredientFormModel();

    model.addAttribute("ingredientFormModel", ingredientFormModel)
    return "viewName";
}

将您的 ingredientsFormModel 附加到 &lt;form&gt; 并使用 . 运算符访问嵌套字段 (注:可以在JSP中访问dish作为requestScope中的常规属性)

<form:form modelAttribute="ingredientFormModel">
    Dish Name: ${dish.name} <br>
    <c:forEach var="ingredient" items="${dish.ingredients}" varStatus="count">
        Ingredient Name: ${ingredient.name} <br>
        <input type="hidden" name="ingredientFormModel.ingredientQuantityList[${count.index}].name" value="${ingredient.name}" />
        Quantity: <input name="ingredientFormModel.ingredientQuantityList[${count.index}].quantity.quantity" type="text" /> </br>
        Unit: <input name="ingredientFormModel.ingredientQuantityList[${count.index}].quantity.unit" type="text"/> </br>
    </c:forEach>         
</form:form>

在您的控制器类中,您可以如下检索对象

@ModelAttribute("ingredientFormModel") IngredientFormModel ingredientFormModel

【讨论】:

  • 所以对我来说,IngredientQuantity 类似于 Contact,Dish 类似于 ContactForm。但是 Spring 如何知道哪些字段被用作 Quantity 等?因为我在 Dish 上设置了
  • 没有。您将附加您希望用户输入的bean。在您的情况下,它将是成分数量列表而不是菜肴。您可以使用 . 运算符访问嵌套元素。我已经用相关细节更新了我的答案。
  • 好的,越来越清楚了,但我不太明白“ProductModel”类的作用是什么?
  • @ModelAttribute("ingredientQuantityList") AutoPopulatedList ingredientQuantityList。请注意,当您迭代列表时,可能会有一些空值。例如,如果用户选择成分 1 和 3,则列表的长度将为 3,但 2 处的值将为空。因此,在从列表中检索值时检查 null
  • 对不起,我刚刚意识到 AutopopulatedList 不能直接在控制器上声明。我们需要的是一个包装模型。我更新了答案。请检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-01
相关资源
最近更新 更多