如何使用JSTL对表示URL路径的String进行编码?

Jos*_*son 32 jsp jstl el uriencoding

使用JSTL对表示URL路径(而不是请求参数)的String进行URL编码的最佳方法是什么?

<c:url value="/user/${user.name}"/>
Run Code Online (Sandbox Code Playgroud)

根据我发现的任何文件,这应该照顾它.但事实并非如此.它精美地编码参数(<c:url value="/user/${user.name}"><c:param name="section" value="employment 4u so good"/></c:url>)但我没有传递任何参数.如何安全地编码一个简单的URL,如上所述,而不用担心${user.name}会是什么?

Bal*_*usC 53

<c:url>在其值中指定,但是它们通过一个嵌套仅指定URL请求参数不编码的URI <c:param>.您链接的IBM文章也没有说明.我认为你把它与"URL重写"混为一谈(实际上只不过是在必要时附加jsessionid).

为了满足您的要求,最好是创建一个自定义EL函数,该函数委托URLEncoder#encode()并更改结果符合URI规则.

<a href="/user/${util:encodeURI(user.name)}">view profile</a>
Run Code Online (Sandbox Code Playgroud)

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", "~");
}
Run Code Online (Sandbox Code Playgroud)

本答案的第2部分中,您可以找到如何声明和注册自定义EL函数的基本启动示例.

  • 奇怪的是,URLEncoder.encode()实际上不是编码URL的正确方法.这是对URL*参数进行编码的正确方法.*例如,它将空格更改为+.正确的技术是新的URI(null,url,null).toASCIIString(),例如将空格更改为%20. (16认同)

J. *_*meo 5

我相信你已经知道这是一个替代解决方案,但我决定使用我最特别的解决方案是使用请求属性.

所以在我的servlet中:

req.setAttribute("myUrl", URLEncoder.encode(myUrl, "UTF-8"));
Run Code Online (Sandbox Code Playgroud)

在我的JSP中:

"...${myUrl}"
Run Code Online (Sandbox Code Playgroud)