【问题标题】:How to URL encode a URL in JSP / JSTL?如何在 JSP / JSTL 中对 URL 进行 URL 编码?
【发布时间】:2013-04-02 03:07:04
【问题描述】:

我想为我的网站创建一个编码的URL。例如,对于这个 URL:“http://google.com/index.html

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

【问题讨论】:

  • 为什么要在 JSP 上执行此操作?你不能只在 servlet 上使用UrlEncoder.encode() 并将数据传递给 JSP 吗?

标签: java html jsp


【解决方案1】:

由于您使用的是 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>

【讨论】:

  • 如何传递一个空的参数值?我试过&lt;c:param name="DocType" value=""/&gt;,但结果是DocType%3d=。我只需要DocType=
  • 我的表达式失败,因为它在那里包含一个单引号。 (Poppo 的 Taqueria - Outpost)。如何通过转义而不是替换来解决?
  • 单引号不需要URL编码。
【解决方案2】:

使用 UrlEncoder.encode() 就是答案。但关键是这种方法不进行百分比编码。使用:

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

【讨论】:

  • 应该是 java.net.URLEncoder 而不是 java.net.UrlEncoder
【解决方案3】:

接受的答案缺少一些有效的 JSP 代码,应该是:

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

<a href="<c:out value='${url}'/>">Link to your client</a>

正如评论指出的那样,另一种选择是使用 JavaScripts encodeURIComponent 方法。

【讨论】:

  • ${url} 和 在这种情况下工作相同
【解决方案4】:

试试你的 JSP 代码:

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

【讨论】:

  • Base64 编码 != URL 编码
猜你喜欢
  • 1970-01-01
  • 2011-08-30
  • 2013-03-04
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-13
相关资源
最近更新 更多