如何使用 JSTL 对表示 URL 路径的字符串进行编码? [英] How to encode a String representing URL path with JSTL?
问题描述
使用 JSTL 对表示 URL 路径(不是请求参数)的字符串进行 URL 编码的最佳方法是什么?
What is the best way to URL-encode a String representing URL path (not request parameter) with JSTL?
<c:url value="/user/${user.name}"/>
根据我找到的任何文档,这应该照顾它.但事实并非如此.它对参数进行了精美的编码 (<c:url value="/user/${user.name}"><c:param name="section" value="employment 4u so good"/><<;/c:url>
) 但我没有传递任何参数.如何安全地编码一个简单的 URL,就像上面一样,而不用担心 ${user.name}
可能是什么?
According to any documentation I find, this should take care of it. But it does not. It encodes parameters beautifully (<c:url value="/user/${user.name}"><c:param name="section" value="employment 4u so good"/></c:url>
) but I'm not passing any parameters. How can I safely encode a simple URL, like above, without fear of what ${user.name}
could be?
推荐答案
<c:url>
不会按照其值中指定的方式对 URI 进行编码,而只是对指定的 URL 请求参数进行编码通过嵌套的
.您链接的 IBM 文章也没有说明.我认为您将它与URL 重写"混淆了(本质上只不过是在必要时附加 jsessionid
).
确实在禁用 cookie 时也能做到这一点.
The <c:url>
does not encode the URI as specified in its value, but just URL request parameters which are specified by a nested <c:param>
. The IBM article which you linked also doesn't tell otherwise. I think that you confused it with "URL rewriting" (which is in essence nothing more than appending the jsessionid
whenever necessary). The <c:url>
indeed does that as well when cookies are disabled.
为了实现您的要求,对路径参数进行 URI 编码,最好是创建一个自定义的 EL 函数,该函数委托给 URLEncoder#encode()
并改变结果符合 URI 规则.
To achieve your requirement, of URI-encoding the path parameters, best is to create a custom EL function which delegates to URLEncoder#encode()
and alters the outcome conform URI rules.
<a href="/user/${util:encodeURI(user.name)}">view profile</a>
与
public static String encodeURI(String value) throws UnsupportedEncodingException {
return URLEncoder.encode(value, "UTF-8")
.replace("+", "%20")
.replace("%21", "!")
.replace("%27", "'")
.replace("%28", "(")
.replace("%29", ")")
.replace("%7E", "~");
}
在 这个答案的第二部分 您可以找到一个基本的启动示例,说明如何声明和注册自定义 EL 函数.
In the 2nd part of this answer you can find a basic kickoff example how to declare and register custom EL functions.
这篇关于如何使用 JSTL 对表示 URL 路径的字符串进行编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!