我正在尝试创建一个通过@ModelAttribute
传递数据的提交按钮。但是,postDTO
中的@PostController
的字段值不变。
非常感谢,麦克。
Controller @GetMapping
@GetMapping("/post")
public String post(Model model) {
List<Post> posts = postRepository.findAllByOrderByPostedAtDesc();
model.addAttribute("postDTO", new PostDTO("", ""));
model.addAttribute("posts", posts);
return "post";
}
html
<ul>
<li th:each="post: ${posts}">
<form th:if="${sessionUser!=null and sessionUser.admin == true}" th:object="${postDTO}" th:action="@{/postEdit}" method="post">
<input type="hidden" th:field="*{id}" th:value="${post.id}">
<button type="submit">Update post</button>
</form>
</li>
</ul>
Controller @PostMapping
@PostMapping("/postEdit")
public String editPost(@ModelAttribute("postDTO") PostDTO postDTO, @ModelAttribute("sessionUser") User sessionUser) {
if (sessionUser.getAdmin()) {
Optional<Post> post = postRepository.findById(postDTO.getId());
if (post.isPresent()) {
redirectAttributes.addAttribute("postId", post.get());
return "redirect:/postEdit/";
}
}
return "redirect:/post";
}
我已经尝试按照Hidden Field Value Blank Thymeleaf中的建议修改html表单。这适用于postDTO
。但是,我的sessionUser.id
也设置为post.id
值。
<form th:if="${sessionUser!=null and sessionUser.admin == true}" th:object="${postDTO}" th:action="@{/postEdit}" method="post">
<input type="hidden" name="id" th:value="${post.id}">
<button type="submit">Update post</button>
</form>
<script th:inline>
是通过Thymeleaf设置隐藏属性的最简单方法。
这是一个有效的示例:
<html>
...
...
<body>
<span hidden id="myData"></span>
...
...
<script th:inline="javascript">
var myData = [[${modelAttributeValue}]];
document.getElementById("myData").textContent = myData;
</script>
以上示例的工作原理:
标识为'myData的隐藏范围元素在脚本标签上方定义。这将创建空的跨度,并使其可供脚本使用。
脚本的th:inline属性将使Thymeleaf对其进行解释。Thymeleaf会将变量“ myData”的值设置为Java服务提供的模型属性值。
id为'myData'的span的文本内容将通过变量设置为Java服务提供的值。
更多信息:
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart