如何在jsp中对字符串进行uri编码?

tes*_*ter 12 java jsp jstl

如果我有一个等于url的字符串"output":

${output} = "/testing/method/thing.do?foo=testing&bar=foo"
Run Code Online (Sandbox Code Playgroud)

在jsp中,我如何将该字符串转换为:

%2Ftesting%2Fmethod%2Fthing.do%3Ffoo%3Dtesting%26bar%3Dfoo
Run Code Online (Sandbox Code Playgroud)

运用

<c:out value="${output}"/>
Run Code Online (Sandbox Code Playgroud)

?我需要以某种方式在c:out中使用URLEncoder.encode(url).

Bal*_*usC 15

标准JSTL标签/功能无法直接实现.这是一个黑客的帮助<c:url>:

<c:url var="url" value=""><c:param name="output" value="${output}" /></c:url>
<c:set var="url" value="${fn:substringAfter(url, '=')}" />
<p>URL-encoded component: ${url}</p>
Run Code Online (Sandbox Code Playgroud)

如果您想更干净地完成它,请创建EL功能.在这个答案的底部你可以找到一个基本的启动示例.你想最终成为:

<p>URL-encoded component: ${my:urlEncode(output, 'UTF-8')}</p>
Run Code Online (Sandbox Code Playgroud)

public static String urlEncode(String value, String charset) throws UnsupportedEncodingException {
    return URLEncoder.encode(value, charset);
}
Run Code Online (Sandbox Code Playgroud)