Thymeleaf构造带变量的URL

Chr*_*ris 51 java jsp thymeleaf

我在控制器中设置了以下代码:

model.set("type", type);
Run Code Online (Sandbox Code Playgroud)

在thymeleaf视图中,我想构建一个带有动作URL的表单:

/mycontroller/{type}
Run Code Online (Sandbox Code Playgroud)

任何想法如何实现这一目标?我没有运气就阅读了百里香的文件.

Sot*_*lis 94

正如user482745在评论(现已删除)中建议的那样,我之前建议的字符串连接

<form th:action="@{/mycontroller/} + ${type}">
Run Code Online (Sandbox Code Playgroud)

在某些网络环境中会失败.

Thymeleaf使用LinkExpression它来解析@{..}表达式.在内部,这使用HttpServletResponse#encodeURL(String).它的javadoc说

对于健壮的会话跟踪,servlet发出的所有URL都应该通过此方法运行.否则,URL重写不能用于不支持cookie的浏览器.

在通过URL完成会话跟踪的Web应用程序中,该部分将附加到附加@{..}之前发出的字符串${..}.你不想要这个.

而是使用文档中建议的路径变量

您还可以以路径变量的形式包含参数,类似于普通参数,但在URL的路径中指定占位符:

<a th:href="@{/order/{id}/details(id=3,action='show_all')}">
Run Code Online (Sandbox Code Playgroud)

所以你的例子看起来像

<form th:action="@{/mycontroller/{path}(path=${type})}"> //adding ending curly brace
Run Code Online (Sandbox Code Playgroud)


lu_*_*_ko 34

如果您不想使用字符串连接(由Sotirios提出),您可以在URL链接中使用表达式预处理:

<form th:action="@{/mycontroller/__${type}__}">
Run Code Online (Sandbox Code Playgroud)


use*_*745 13

你需要@ {}内的连接字符串.

<form th:action="@{'/mycontroller/' + ${type}}">
Run Code Online (Sandbox Code Playgroud)

@ {}用于URL重写.URL重写的一部分是跟踪会话.第一次用户请求URL,应用服务器添加到url ;jsessionid=somehexvalue并使用jsessionid生成cookie.当客户端在下一个请求期间发送cookie时,服 如果服务器知道客户端支持cookie,则服务器不会在URL中保留addind jsessionid.

我首选的方法是使用管道语法(|)进行文字替换.

<form th:action="@{|/mycontroller/${type}|}">
Run Code Online (Sandbox Code Playgroud)

Thymeleaf路径变量语法是

<form th:action="@{/mycontroller/{pathParam}(pathParam=${type}}">
Run Code Online (Sandbox Code Playgroud)

参考: Thymeleaf标准URL语法

  • 我也更喜欢字面替换,因为它更清晰且易于维护。thymeleaf 语法​​对于简单的任务来说太复杂了。 (2认同)

Wit*_*rba 5

你需要的是:

<a th:href="@{/mycontroller/{type}(type=${type})}">
Run Code Online (Sandbox Code Playgroud)

文档:

这里有很大帮助:http : //www.thymeleaf.org/doc/articles/standardurlsyntax.html。我从那里使用的是:

您还可以以类似于普通参数的路径变量的形式包含参数,但在 URL 路径中指定一个占位符:

<a th:href="@{/order/{id}/details(id=3,action='show_all')}">

... 更重要的是:一个 URL 表达式,如:

<a th:href="@{/order/details(id=${order.id})}">

  • 需要提及的一件事是参数必须全部位于链接表达式的末尾。这是不正确的语法:`@{/order/{id}(id=${anIdExpression})/detail/{detail}(detail=${aDetailExpression)}` 但这是正确的:`@{/order/{id }/detail/{detail}(id=${anIdExpression}, detail=${aDetailExpression)}` 文档在这一点上不是很清楚,所以我想我可以节省其他人花在试用和错误。 (2认同)