spring-boot - 不将额外的参数从控制器传递到模板
问题描述
在我的 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=""/>
是空的。为什么?必须是真值
解决方案
手动指定名称和值(而不是使用th:field
),如下所示:
<input type="hidden" id="isAdd"
name="isAdd"
th:value="${isAdd}"/>
请注意,这不会设置绑定,但我想这对于隐藏字段来说还是可以的。
推荐阅读
- html - 获取对包含特定 RDF 知识来源的微数据的文档的引用
- python-3.x - Django表单外键字段只读在更新表单期间给出值错误
- python - 如何使用正则表达式提取多个字符串?
- ios - 在后台 NSURLSession 中获取数据
- firebase - Firebase 托管设置,但仅适用于域名而不是网站的文件
- python-3.x - 在python中将日期字符串转换为带有时区的时间戳
- flutter - 如何在 Flutter Web 中居中 AppBar 内容
- c# - EF Core EnsureDeleted 抛出“使用用户 'sa' 登录失败”
- apache-spark - 如何在 SQL 查询中使用变量?
- postgresql - 使用 pg_trgm 将小表(<1,000 行)与大表(>100m 行)匹配——最有效的方法?