java 如何在jsp中对字符串进行uri编码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4952659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to uri encode a string in jsp?
提问by tester
if I have a string "output" that equals a url:
如果我有一个等于 url 的字符串“输出”:
${output} = "/testing/method/thing.do?foo=testing&bar=foo"
in the jsp,how would I convert that string into:
在jsp中,我将如何将该字符串转换为:
%2Ftesting%2Fmethod%2Fthing.do%3Ffoo%3Dtesting%26bar%3Dfoo
using
使用
<c:out value="${output}"/>
? I need to URLEncoder.encode(url) in the c:out somehow.
? 我需要以某种方式在 c:out 中使用 URLEncoder.encode(url)。
回答by BalusC
It's not directly possible with standard JSTL tags/functions. Here's a hack with help of <c:url>
:
使用标准 JSTL 标记/函数无法直接实现。这是一个 hack 的帮助<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>
If you want to do it more cleanly, create an EL function. At the bottom of this answeryou can find a basic kickoff example. You'd like to end up as:
如果你想做得更干净,创建一个 EL 函数。在这个答案的底部,您可以找到一个基本的启动示例。你想最终成为:
<p>URL-encoded component: ${my:urlEncode(output, 'UTF-8')}</p>
with
和
public static String urlEncode(String value, String charset) throws UnsupportedEncodingException {
return URLEncoder.encode(value, charset);
}
回答by limc
Try this:-
试试这个:-
<c:out value="${output}" escapeXml="true" />
Granted, this will only escape special characters from XML.
当然,这只会从 XML 中转义特殊字符。