Reputation: 299
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 this place)
Whenever the button is clicked, "The website cannot display the page"
error is shown.
But when you manually change the "%"
symbol to "%25"
like this "Population of 91%25 in this place
",then the correct page is displayed.
Also whenever the "%"
symbol is placed at last like this "In this place Population of 91%
", then the page is correctly displayed but i noticed that in the address bar its still shown as "%"
and not as "%25"
and still its working.
When I searched around, its mentioned only to use the other methods like encodeURI() & encodeURIComponent().
Can you suggest me a solution while still using the encodeURL
method to display the pages correctly even if there is a "%"
symbol. Should i use replace()
or why isnt the encodeURL()
method working correctly?
Upvotes: 1
Views: 6828
Reputation: 1979
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.
Upvotes: 0
Reputation: 2379
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');
?
Upvotes: 1
Reputation: 1108712
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>
Upvotes: 0