What is the best way to URL-encode a String representing URL path (not request parameter) with JSTL?
<c:url value="/user/${user.name}"/>
According to any documentation I find, this should take care of it. But it does not. It encodes parameters beautifully (<c:url value="/user/${user.name}"><c:param name="section" value="employment 4u so good"/></c:url>
) but I'm not passing any parameters. How can I safely encode a simple URL, like above, without fear of what ${user.name}
could be?
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).To achieve your requirement, best is to create a custom EL function which delegates to
URLEncoder#encode()
and alters the outcome conform URI rules.with
In the 2nd part of this answer you can find a basic kickoff example how to declare and register custom EL functions.
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:
and in my JSP:
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:
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:
Keep it simple in this way: