How to URL encode a URL in JSP / JSTL?

前端 未结 4 442
北海茫月
北海茫月 2020-12-03 11:10

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

相关标签:
4条回答
  • 2020-12-03 11:27

    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>
    
    0 讨论(0)
  • 2020-12-03 11:31

    Try in your JSP code:

    Base64.encodeBase64( "http://google.com/index.html")
    
    0 讨论(0)
  • 2020-12-03 11:42

    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.

    0 讨论(0)
  • 2020-12-03 11:44

    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")
    
    0 讨论(0)
提交回复
热议问题