【问题标题】:Thymeleaf path variable is not working. What am I doing wrong?Thymeleaf 路径变量不起作用。我究竟做错了什么?
【发布时间】:2020-06-02 22:01:08
【问题描述】:

有些东西让我无法在 HTML 表单中使用 Thymeleaf 和 HTML 设置路径变量。 我想简单地在表单中输入 33 并获取 localhost:8080/blog/33 作为 url,但我只能获取查询字符串或格式错误的括号等。

一些示例尝试和结果:
th:action="@{/blog/{id}(id = ${id})}"
本地主机:8080/blog/?id=33

th:action="@{/blog/+ ${id}}"
localhost:8080/blog/+%20$%7Bid%7D?id=33

我想要的是:
本地主机:8080/blog/33

此表单的完整代码如下:

<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
    <head>
        <title>Form Submission</title>
        <style>
            button{
                margin-top:20px;
                width: 250px;
            }
        </style>
    </head>
    <body>
        <h2>Delete Entry</h2>
        <form action="#" th:action="@{/blog/{id}(id = ${id})}" th:object="${blog}" method="get" >  
            <fieldset>
                <p>Delete ID: <input type="text" th:field="*{id}" required /></p>
                <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
            </fieldset>
        </form>
        <button onclick="window.location.href = '/'">Menu</button>
    </body>
</html>

【问题讨论】:

  • 如何使用标准连接,不使用特殊 URL @{...} 语法:th:action="'/blog/' + ${id}"。您不需要明确需要主机和端口部分(这一切都发生在应用程序内 - 我假设)。 CAVEAT - 我使用 Thymeleaf,但不是 Spring - 所以这可能会有所作为。
  • 只是为了添加到我的第一条评论中-出于某种原因,您的第一个示例对我来说很好。所以,直接从我的代码粘贴,th:action="@{/blog/{id}(id = ${id})}" 给了我以下信息:http://localhost:7000/blog/33。奇数。
  • 我刚才粘贴了你的第一个例子 th:action="'/blog/' + ${id}" 结果是 localhost:8080/blog/null?id=33。我已经尝试了一切!

标签: html forms spring-boot thymeleaf


【解决方案1】:

此语法正确:@{/blog/{id}(id = ${id})}

你得到localhost:8080/blog/?id=33的原因可能是因为创建表单时${id}是空的,当你点击提交按钮时,它是在url中添加?id=33(因为方法是get并且您的输入具有相同的name="id":&lt;input type="text" th:field="*{id}" required /&gt;

没有 html/thymeleaf 方式(没有 javascript)可以将表单字段放入 URL 的路径部分(如果这是您所期望的)。如果您希望发生这种情况,您必须使用 javascript 库。

【讨论】:

    猜你喜欢
    • 2016-05-27
    • 2019-05-26
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 2016-07-18
    • 2020-08-30
    相关资源
    最近更新 更多