2013-04-10 84 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")