Thymeleaf - 如何使用Hashmap

时间:2014-11-06 14:11:48

标签: spring-mvc thymeleaf

我想使用HashMap,因为以下示例使用了List:http://www.thymeleaf.org/doc/thymeleafspring.html#dynamic-fields 然而,我试过没有效果。

编辑:我正在提供一些代码。所以问题是我想在表单中使用hashmap产品,我上面提供的示例很适合列表,但是我想将它与hashmap一起使用。 实体:

@Entity
@Table(name = "meals")
public class Meal extends BaseEntity{
@NotEmpty
private String name;
@NotEmpty
private String recipe;
private String image;
private double cost;
@NotNull
private int kcal;
@NotNull
private int proteins;
@NotNull
private int fats;
@NotNull
private int carbs;
@NotNull
private int portions;
@ElementCollection
@Column(name = "quantity")
private Map<Product, Integer> products = new HashMap<>();
//getters & setters

形式:

<!DOCTYPE html>
<html lang="en">
<head th:replace="fragments/headTag :: headTag"/>
<body>
<div class="container">
<div th:replace="fragments/bodyHeader :: bodyHeader"></div>
<h2 th:text="#{meals.new.title}"/>
<form th:object="${meal}" th:method="post" th:action="@{${#httpServletRequest.servletPath}}"
      enctype="multipart/form-data"
      class="form-horizontal" id="newMealForm">
//other fields
    <div class="control-group" th:classappend="${#fields.hasErrors('products')} ? error">
        <label class="control-label" th:text="#{meals.products}"/>

        <div class="controls"><span class="help-inline"
                                                              th:errors="*{products}">[error]</span>
            <table class="table table-striped">
                <thead>
                <tr>
                    <th th:text="#{product.name}"/>
                    <th th:text="#{product.quantity}"/>
                    <th><button type="submit" name="addProduct" th:text="#{meals.addProduct}"/></th>
                </tr>
                </thead>
                <tbody>
                <tr th:each="products,rowStat : *{products}">
                    <td><input type="text" th:field="*{products[__${rowStat.index}__].value}" /></td>
                    <td>
                        <input type="number" th:field="*{products}" />
                    </td>
                    <td>
                        <button type="submit" name="removeProduct"
                                th:value="${rowStat.index}" th:text="#{meals.removeProduct}"/>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
    <div class="form-actions">
        <button type="submit" class="btn btn-primary" th:text="#{submit}"/>
    </div>
 </form>
 </div>
 <div th:replace="fragments/footer :: footer"></div>
</body>
</html>

添加/删除行的控制器方法:

@RequestMapping(value="/meals/new", params={"addProduct"})
public String addProduct(final Meal meal, final BindingResult bindingResult) {
    meal.getProducts().put(new Product(), 1);
    return "/meals/new";
}

@RequestMapping(value="/meals/new", params={"removeProduct"})
public String removeRow(
        final Meal meal, final BindingResult bindingResult,
        final HttpServletRequest req) {
    final Integer rowId = Integer.valueOf(req.getParameter("removeProduct"));
    meal.getProducts().remove(rowId.intValue());
    return "/meals/new";
}

我遇到的错误是:

org.springframework.beans.InvalidPropertyException: Invalid property 'products[0]' of bean class [org.cybuch.incessantfeasting.model.Meal]: Invalid index in property path 'products[0]'; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'org.cybuch.incessantfeasting.model.Product' for property 'null'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type org.cybuch.incessantfeasting.model.Product for value '0'; nested exception is java.lang.IllegalArgumentException: Unable to parse '0'

1 个答案:

答案 0 :(得分:1)

我前段时间已经解决了这个问题,所以我想与解决方案分享会很好。我已经使用包装器将映射更改为控制器中的列表,因此它是List,其中ProductQuantity类包含2个字段 - 产品和字符串数量。之后,我将该列表转换为映射并保存到数据库中。