首页 > 解决方案 > 不将额外的参数从控制器传递到模板

问题描述

在我的 Spring Boot 2 项目中。

控制器:

@Controller
public class CategoryController {
    @Value("${spring.application.name}")
    private String appName;

  @RequestMapping("category/add")
    public String addtCategory(Model model) {
        model.addAttribute("isAdd", true);
        model.addAttribute("category", new Category());
        return "category";
    }

通过这个添加额外的参数:

model.addAttribute("isAdd", true);

模板:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:text="${appName}">Category template title</title>
    <link th:href="@{/public/style.css}" rel="stylesheet"/>
    <meta charset="UTF-8"/>
</head>
<body>
<div class="container">
    <form method="post" action="#" th:object="${category}" th:action="@{/category}">
        <h3>Edit Category</h3>
        <input type="hidden" id="isAdd" th:field="${isAdd}"/>
        <input type="hidden" id="id" th:field="*{id}"/>
        <input type="text" placeholder="Name" id="name" th:field="*{name}"/>
        <input type="hidden" id="created" th:field="*{created}"/>
        <textarea placeholder="Description" rows="5" id="description"
                  th:field="*{description}"></textarea>
        <input type="submit" value="Submit"/>
    </form>

    <div class="result_message" th:if="${submitted}">
        <h3>Your category has been submitted.</h3>
        <p>Find all categories <a href="/categories">here</a></p>
    </div>
</div>
</body>
</html>

并生成html:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="/public/style.css" rel="stylesheet"/>
    <meta charset="UTF-8"/>
</head>
<body>
<div class="container">
    <form method="post" action="/category"><input type="hidden" name="_csrf" value="5cda30d8-6f11-4e82-bb06-a8eb141afb41"/>
        <h3>Edit Category</h3>
        <input type="hidden" id="isAdd" name="" value=""/>
        <input type="hidden" id="id" name="id" value="0"/>
        <input type="text" placeholder="Name" id="name" name="name" value=""/>
        <input type="hidden" id="created" name="created" value=""/>
        <textarea placeholder="Description" rows="5" id="description" name="description"></textarea>
        <input type="submit" value="Submit"/>
    </form>


</div>
</body>
</html>

如您所见:

 <input type="hidden" id="isAdd" name="" value=""/>

是空的。为什么?必须是

标签: spring-bootthymeleaf

解决方案


手动指定名称和值(而不是使用th:field),如下所示:

<input type="hidden" id="isAdd"
                   name="isAdd"
                   th:value="${isAdd}"/>

请注意,这不会设置绑定,但我想这对于隐藏字段来说还是可以的。


推荐阅读