Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
772 views
in Technique[技术] by (71.8m points)

jsp - How to encode a String representing URL path with JSTL?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...