How to encode a String representing URL path with JSTL?
I'm sure you already knew this was an alternative solution, but I decided for my particular use the most elegant solution was to use a request attribute.
So in my servlet:
req.setAttribute("myUrl", URLEncoder.encode(myUrl, "UTF-8"));
and in my JSP:
"...${myUrl}"
The <c:url>
does not encode the URI as specified in its value, but just URL request parameters which are specified by a nested <c:param>
. The IBM article which you linked also doesn't tell otherwise. I think that you confused it with "URL rewriting" (which is in essence nothing more than appending the jsessionid
whenever necessary). The <c:url>
indeed does that as well when cookies are disabled.
To achieve your requirement, of URI-encoding the path parameters, best is to create a custom EL function which delegates to URLEncoder#encode()
and alters the outcome conform URI rules.
<a href="/user/${util:encodeURI(user.name)}">view profile</a>
with
public static String encodeURI(String value) throws UnsupportedEncodingException {
return URLEncoder.encode(value, "UTF-8")
.replace("+", "%20")
.replace("%21", "!")
.replace("%27", "'")
.replace("%28", "(")
.replace("%29", ")")
.replace("%7E", "~");
}
In the 2nd part of this answer you can find a basic kickoff example how to declare and register custom EL functions.
you could use the jakarta String TagLib, which has a encodeUrl tag: http://jakarta.apache.org/taglibs/doc/string-doc/string-1.1.0/index.html#encodeUrl
Follow these steps to configure your web application with this tag library:
- Copy the tag library descriptor file to the /WEB-INF subdirectory of your web application.
- Copy the tag library JAR file to the /WEB-INF/lib subdirectory of your web application.
- Add a element to your web application deployment descriptor in /WEB-INF/web.xml as said in the above link
To use the tags from this library in your JSP pages, add the following directive at the top of each page:
below is the example of usage in jsp:
<a href="str:decodeUrl>${URL}</str:decodeUrl)"/>