2012-01-03 124 views
1

我想在jsp中使用encodeURL方法来编码带有“%”符号的URL。如何使用特殊字符“百分比”对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()方法正常工作?

回答

1

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

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

的结果你代码是:

%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'); 

0

在你的榜样,您可以使用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标签将URL编码的价值属性。我刚刚遇到了一种情况,我需要生成一个包含以磅符号开头的值的查询字符串的URL。没有url编码,井号被浏览器解释为锚点部分的开始。我添加了c:param标记,并对井号进行了编码,从而在链接后允许预期的行为。