【问题标题】:How to encode a URL with the special character "percentage"?如何使用特殊字符“百分比”对 URL 进行编码?
【发布时间】:2012-01-03 13:45:36
【问题描述】:

我正在尝试在 jsp 中使用 encodeURL 方法对带有“%”符号的 URL 进行编码。

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

每当单击按钮时,都会显示"The website cannot display the page" 错误。

但是当您手动将"%" 符号更改为"%25" 像这样“Population of 91%25 in this place”时,就会显示正确的页面。

此外,每当 "%" 符号最后像这样“In this place Population of 91%”放置时,页面就会正确显示,但我注意到在地址栏中它仍然显示为 "%" 而不是 "%25" 和仍然有效。

当我四处搜索时,它只提到使用其他方法,如encodeURI() & encodeURIComponent().

您能否建议我一个解决方案,同时仍然使用encodeURL 方法正确显示页面,即使有"%" 符号。我应该使用replace() 还是为什么encodeURL() 方法不能正常工作?

【问题讨论】:

    标签: java jsp url encoding


    【解决方案1】:

    考虑使用URLEncoderURLDecoder

    【讨论】:

      【解决方案2】:

      你的代码的结果是:

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

      您应该只对查询字符串值进行编码。

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

      ?

      【讨论】:

        【解决方案3】:

        HttpServletResponse#encodeURL() 方法实际上有一个误导性的名称。阅读javadoc 以了解它的真正作用(如有必要,附加jsessionid)。另请参阅 In the context of Java Servlet what is the difference between URL Rewriting and Forwarding? 以了解 JSP/Servlet 世界中的歧义。

        在 servlet 端,您需要 URLEncoder#encode()

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

        然而,在 JSP 端,您需要 JSTL <c:url> 标记 (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>
        

        【讨论】:

          【解决方案4】:

          在您的示例中,您可以使用c:urlc:param 标签:

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

          特别是,c:param 标记将对 value 属性进行 url 编码。我刚刚遇到了一种情况,我需要生成一个带有查询字符串的 URL,该查询字符串包含一个以井号开头的值。如果没有 url 编码,井号会被浏览器解释为锚部分的开始。我添加了c:param 标签,并且井号被编码,允许点击链接时的预期行为。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-04-17
            • 2022-10-21
            • 2018-09-09
            相关资源
            最近更新 更多