首页 > 解决方案 > 如何使用 thymleaf 中的另一个对象设置对象的值?

问题描述

我正在传递一个帖子对象和当前的loggedInUser,我想将“*{author}”的值设置为“${loggedInUser.uid}”。

    @GetMapping("/showNewBlogForm")
    public String showNewPostForm(Model model) {
        Post post = new Post();
        model.addAttribute("post", post);
        model.addAttribute("loggedInUser", getLoggedInUser());
        return "new_post";
    }

<div class="container">
        <h2>Create Blog</h2>
        <h2 th:text="${loggedInUser.uid}"></h2>
        <form action="#" th:action="@{/publishPost}" th:object="${post}" method="post">
            <input type="text" th:field="*{title}" placeholder="Title" class="form-control mb cp-4" required>
            <input type="text" th:field="*{excerpt}" placeholder="Excerpt" class="form-control mb cp-4" required>
            <textarea type="text" rows="10" th:field="*{content}" placeholder="Content" class="form-control mb cp-4" required></textarea>
            <input type="text" th:value="${loggedInUser.uid}" th:field="*{author}" class="form-control mb cp-4">
            <input type="text" th:field="*{tagsString}" placeholder="Tags" class="form-control mb cp-4">
            <button type="submit" class="btn btn-info col-2"> Publish </button>
        </form>

        <hr>

        <a th:href = "@{/}"> Back to Home Page</a>
    </div>
[1]:https ://i.stack.imgur.com/7o7d5.png

标签: thymeleaf

解决方案


只需替换th:field="*{author}"name="author"

<input type="text" th:value="${loggedInUser.uid}" name="author" class="form-control mb cp-4">

由于th:value输入将默认包含“loggedInUser”的uid。

由于name输入的值将Post在提交表单时绑定到对象的“作者”字段。


推荐阅读