How to encode a URL with the special character “percentage”?

前端 未结 4 1591
你的背包
你的背包 2021-01-24 08:43

I am trying to use the encodeURL method in a jsp to encode a URL with \"%\" symbol.

response.encodeURL(/page1/page2/view.jsp?name=Population of 91% in

相关标签:
4条回答
  • 2021-01-24 08:47

    Consider using URLEncoder and URLDecoder.

    0 讨论(0)
  • 2021-01-24 08:47

    The result of your code is :

    %2Fpage1%2Fpage2%2Fview.jsp%3Fname%3DPopulation%20of%2091%25%20in%20this%20place
    

    You should encode only the query string value.

    ... = "/page1/page2/view.jsp?name=" + URLEncoder.encode('Population of 91% in this place');
    

    ?

    0 讨论(0)
  • 2021-01-24 08:57

    In your example, you can use the c:url and c:param tags:

    <c:url value="/page1/page2/view.jsp">
        <c:param name="name" value="Population of 91% in this place" />
    </c:url>
    

    In particular, the c:param tag will url-encode the value attribute. I just ran into a situation where I needed to generate a URL with a querystring containing a value that started with a pound sign. Without url-encoding, the pound sign was interpreted by the browser as the start of the anchor portion. I added the c:param tag, and the pound sign was encoded, allowing expected behavior when following the link.

    0 讨论(0)
  • 2021-01-24 08:58

    The HttpServletResponse#encodeURL() method has actually a misleading name. Read the javadoc to learn what it really does (appending the jsessionid if necessary). See also In the context of Java Servlet what is the difference between URL Rewriting and Forwarding? to learn about ambiguties in JSP/Servlet world.

    In the servlet side, you need URLEncoder#encode() instead:

    String url = "/page1/page2/view.jsp?name=" + URLEncoder.encode("Population of 91% in this place", "UTF-8");
    // ...
    

    In the JSP side, however, you need the JSTL <c:url> tag instead (avoid Java code in JSP!):

    <%@ page pageEncoding="UTF-8" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    ...
    
    <c:url var="url" value="/page1/page2/view.jsp">
      <c:param name="name" value="Population of 91% in this place" />
    </c:url>
    
    <a href="${url}">link</a>
    
    <form action="${url}">
      <input type="submit" value="button" />
    </form>
    
    0 讨论(0)
提交回复
热议问题