如何动态生成表格形式的表格?

时间:2019-06-12 23:51:32

标签: spring thymeleaf

我要将属性传递到模型中,并确保它不为null ...

控制器:

@GetMapping(Mappings.MAIN) // AliasFor @RequestMapping(method = RequestMethod.GET)
    public String getMainView(Model model,
                              @ModelAttribute(AttributeNames.VIEW_RECIPE) ViewRecipe recipe){

        log.info(recipe.toString());

        if(recipe==null){
            recipe = new ViewRecipe();
            recipe.setIngredientList(new ArrayList<>());

        }
        model.addAttribute(AttributeNames.VIEW_RECIPE, recipe);


        return ViewNames.MAIN_VIEW;
    }

实用程序类:

public class ViewNames {
    public static final String HOME = "home";

public class AttributeNames { 
    public static final String VIEW_RECIPE="view-recipe";

public class Mappings {
    public static final String HOME ="home";

胸腺模板:

<form id="get-recalculated-recipe" action="#" method="post">
    <table>
        <tr><th>Quantity</th>
            <th>Unit</th>
            <th>Ingredient Name</th>
            <th>Multiplier</th>

        </tr>
        <tr th:each="ing : ${view-recipe.ingredientList}">
            <td>
            <input type="text" th:field="*{ing.quantity}"/>
            </td>
            <td>
                <input type="text" th:field="*{ing.unit}"/>
            </td>
            <td>
                <input type="text" th:field="*{ing.ingredientName}"/>
            </td>
            <td>
                <input type="text" th:field="*{ing.ingredientName}"/>
            </td>
        </tr>
    </table>
</form>

1 个答案:

答案 0 :(得分:1)

首先,您不能确保成分列表不为空。考虑一下您调用控制器并且配方不为空的情况,但是配方的成分列表属性为空。它将作为null发送到您的视图。您可以将其更改为例如:

*{...}

第二,您在th:字段中使用选择表达式(<form id="get-recalculated-recipe" th:object="${view-recipe}" action="#" method="post"> ),这很好,但是您还需要在表单中定义一个命令对象,并从输入中引用它。您可以这样将命令对象添加到表单中:

<tr th:each="ing, iter : ${view-recipe.ingredientList}">
    <td>
    <input type="text" th:value="${ing.quantity}" th:field="*{ingredientList[__${iter.index}__].quantity}"/>
    </td>
    <td>
        <input type="text" th:value="${ing.unit}" th:field="*{ingredientList[__${iter.index}__].unit}"/>
    </td>
    <td>
        <input type="text" th:value="${ing.ingredientName}" th:field="*{ingredientList[__${iter.index}__].ingredientName}"/>
    </td>
</tr>

并更改您的th:字段以使用迭代器对其进行引用,以便在您发布表单时提交输入信息。此外,在页面加载时还添加了th:value以实际获取属性的当前值:

{{1}}

我建议您看看https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html,它将对您将来有所帮助。

相关问题