2013-04-10 82 views
10

我想为我的网站创建编码为URL。举例来说,对于此URL:“http://google.com/index.html如何在JSP中对URL进行URL编码?

我想通过URL编码将此URL提供给客户端。

+0

你为什么要在JSP上这样做?难道你不能在servlet上使用[UrlEncoder.encode()](http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html)并将数据传递给JSP? – 2013-04-10 10:21:07

回答

27

由于您使用JSP,我会坚持到JSTLnot use scriptlets。您可以使用JSTL标签<c:url /> in combination with <c:param />

<c:url value="/yourClient" var="url"> 
    <c:param name="yourParamName" value="http://google.com/index.html" /> 
</c:url> 

<a href="${url}">Link to your client</a> 

这将导致:

<a href="/yourClient?yourParamName=http%3a%2f%2fgoogle.com%2findex.html">Link to your client</a> 
+0

如何传递一个空的参数值?我已经尝试过''但它会产生'DocType%3d ='。我只需要'DocType ='。 – 2015-03-30 06:58:15

+0

空值适用于我。 – 2015-03-30 07:31:44

-8

尝试在你的JSP代码:

Base64.encodeBase64("http://google.com/index.html") 
+13

Base64编码!= URL编码 – 2013-04-10 10:21:23

3

使用UrlEncoder.encode()就是答案。但重要的是,这种方法没有百分比编码。使用:

java.net.UrlEncoder.encode(stringOfURL,"UTF-8").replace("+","%20")