如何使用JSTL对表示URL路径的字符串进行编码? [英] How to encode a String representing URL path with JSTL?

查看:479
本文介绍了如何使用JSTL对表示URL路径的字符串进行编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用JSTL对代表URL路径(不是请求参数)的字符串进行URL编码的最佳方法是什么?

What is the best way to URL-encode a String representing URL path (not request parameter) with JSTL?

<c:url value="/user/${user.name}"/>

根据我找到的任何文档,应该照顾它.但事实并非如此.它可以很好地编码参数(<c:url value="/user/${user.name}"><c:param name="section" value="employment 4u so good"/></c:url>),但我没有传递任何参数.如何像上面一样安全地编码一个简单的URL,而不用担心${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?

推荐答案

<c:url>不会按照其值中指定的URI编码,而只是由嵌套的<c:param>指定的URL请求参数编码.您链接的IBM文章也没有其他说明.我认为您将其与"URL重写"(实际上只是在必要时附加jsessionid)相混淆.在禁用Cookie的情况下,<c:url>确实也可以做到这一点.

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.

要满足您对URI参数编码路径参数的要求,最好是创建一个自定义的EL函数,该函数委托给

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>

使用

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", "~");
}

第二部分中您可以找到一个基本的启动示例,该示例演示如何声明和注册自定义EL函数.

In the 2nd part of this answer you can find a basic kickoff example how to declare and register custom EL functions.

这篇关于如何使用JSTL对表示URL路径的字符串进行编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆