带有变量的 Thymeleaf 构造 URL [英] Thymeleaf construct URL with variable

查看:31
本文介绍了带有变量的 Thymeleaf 构造 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码在我的控制器中设置一个变量:

I have the following code setting a variable in my controller:

model.set("type", type);

在 thymeleaf 视图中,我想构建一个带有 action url 的表单:

In the thymeleaf view I want to construct a form with action url:

/mycontroller/{type}

任何想法如何实现这一目标?我读了 thymeleaf 文档,但运气不佳.

Any ideas how to achieve this? I've read thymeleaf documentation with no luck.

推荐答案

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

As user482745 suggests in the comments (now deleted), the string concatenation I previously suggested

<form th:action="@{/mycontroller/} + ${type}">

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

will fail in some web contexts.

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

Thymeleaf uses LinkExpression that resolves the @{..} expression. Internally, this uses HttpServletResponse#encodeURL(String). Its javadoc states

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

For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

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

In web applications where the session tracking is done through the URL, that part will be appended to the string emitted for @{..} before the ${..} is appended. You don't want this.

改为使用文档中建议的路径变量

Instead, use path variables as suggested in the documentation

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

You can also include parameters in the form of path variables similarly to normal parameters but specifying a placeholder inside your URL’s path:

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

所以你的例子看起来像

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

这篇关于带有变量的 Thymeleaf 构造 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆