java 转义 & 在 URL 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2197993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:00:37  来源:igfitidea点击:

Escaping & in a URL

javajspurluri

提问by user265950

I am using jsps and in my url I have a value for a variable like say "L & T". Now when I try to retrieve the value for it by using request.getParameterI get only "L". It recognizes "&" as a separator and thus it is not getting considered as a whole string.

我正在使用 jsps,在我的 url 中,我有一个变量值,比如“L & T”。现在,当我尝试通过使用检索它的值时,request.getParameter我只得到“L”。它将“&”识别为分隔符,因此不会将其视为整个字符串。

How do I solve this problem?

我该如何解决这个问题?

回答by Bozho

java.net.URLEncoder.encode("L & T", "utf8")

this outputs the URL-encoded, which is fine as a GET parameter:

这将输出 URL 编码,作为 GET 参数很好:

L+%26+T

回答by Erik

A literal ampersand in a URL should be encoded as: %26

URL 中的文字与符号应编码为: %26

// Your URL
http://www.example.com?a=l&t

// Encoded
http://www.example.com?a=l%26t

回答by Ben Zotto

You need to "URL encode" the parameters to avoid this problem. The format of the URL query string is: ...?<name>=<value>&<name>=<value>&<etc>All <name>s and <value>s need to be URL encoded, which basically means transforming all the characters that could be interpreted wrongly (like the &) into %-escaped values. See this page for more information: http://www.w3schools.com/TAGS/ref_urlencode.asp

您需要对参数进行“URL 编码”以避免此问题。URL 查询字符串的格式是: ...?<name>=<value>&<name>=<value>&<etc>所有<name>s 和<value>s 都需要进行 URL 编码,这基本上意味着将所有可能被错误解释的字符(如 &)转换为 % 转义值。有关更多信息,请参阅此页面:http: //www.w3schools.com/TAGS/ref_urlencode.asp

If you're generatingthe problem URL with Java, you use this method: String str = URLEncoder.encode(input, "UTF-8");

如果您使用 Java生成问题 URL,请使用以下方法: String str = URLEncoder.encode(input, "UTF-8");

Generating the URL elsewhere (some templates or JS or raw markup), you need to fix the problem at the source.

在别处生成 URL(一些模板或 JS 或原始标记),您需要在源头修复问题。

回答by xuesheng

You can use UriUtils#encode(String source, String encoding)from Spring Web. This utility class also provides means for encoding only some parts of the URL, like UriUtils#encodePath.

您可以UriUtils#encode(String source, String encoding)Spring Web使用。该实用程序类还提供了仅对 URL 的某些部分进行编码的方法,例如UriUtils#encodePath.