【问题标题】:Thymeleaf: Pass data in hidden input fieldThymeleaf:在隐藏的输入字段中传递数据
【发布时间】:2020-06-20 02:36:48
【问题描述】:

我正在尝试创建一个通过@ModelAttribute 传递数据的提交按钮。但是@PostControllerpostDTO的字段值不变。

非常感谢和亲切的问候,迈克。

控制器@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>

控制器@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>

【问题讨论】:

    标签: java html spring-boot thymeleaf


    【解决方案1】:

    &lt;script th:inline&gt; 是通过 Thymeleaf 设置隐藏属性的最简单方法。

    这是一个工作示例:

    
    <html>
     ...
     ...
    <body>
        <span hidden id="myData"></span>
        ...
        ...
        <script th:inline="javascript">
    
            var myData = [[${modelAttributeValue}]];
    
            document.getElementById("myData").textContent = myData; 
    
        </script>
    

    上面的例子是这样工作的:

    1. id 为“myData”的隐藏 span 元素在脚本标记上方定义。 这将创建空跨度并使其准备好供脚本使用。

    2. 脚本的 th:inline 属性将使 Thymeleaf 解释它。 Thymeleaf 会将变量“myData”的值设置为 Java 服务提供的模型属性值。

    3. id 为“myData”的 span 的文本内容将通过变量设置为 Java 服务提供的值。

    更多信息:

    https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#script-inlining-javascript-and-dart

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 2017-11-16
      • 2017-05-30
      • 2018-10-01
      • 1970-01-01
      • 2020-01-29
      相关资源
      最近更新 更多