22

I want to create an encoded URL for my site. Say for example, for this URL: "http://google.com/index.html"

I want to give this URL to the client by URL encoding it.

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
Abrah
  • 341
  • 2
  • 3
  • 8
  • Why would you want to do this on a JSP ? Can't you just use [UrlEncoder.encode()](http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html) on the servlet and pass the data to the JSP ? – Deepak Bala Apr 10 '13 at 10:21

3 Answers3

40

Since you are using JSP, I would stick to JSTL and not use scriptlets. You could use the JSTL tag <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>

This will result in:

<a href="/yourClient?yourParamName=http%3a%2f%2fgoogle.com%2findex.html">Link to your client</a>
Community
  • 1
  • 1
Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
5

Using UrlEncoder.encode() is the answer. But the point is that this method doesn't percentage encode. Use:

java.net.UrlEncoder.encode(stringOfURL,"UTF-8").replace("+","%20")
radoh
  • 4,554
  • 5
  • 30
  • 45
Mohsen Abasi
  • 2,050
  • 28
  • 30
1

The accepted answer is missing some JSP code to be valid, it should be:

<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>

As a comment pointed out, another option is to use JavaScripts encodeURIComponent method.