我的网址如下。
http://localhost:8080/servlet?user=John&message=hai&hello&recipient=scott
在上面的网址中,我有 3 个请求参数,如下所示。
user=John
message=hai&hello
recipient=scott
这里的问题是 message
请求参数的值。因为这里它的值包含与号 (&)。当我尝试 request.getParameter("message")
时,我只得到 hai
而不是 hai&hello
。我该如何解决这个问题?
谢谢!
最佳答案
试试这个,而不是....&message=hi%26hello....
。我的意思是,对其进行编码。
[已编辑]
正如您所说,您无法控制它,它是遗留应用程序,他们无法修复它;那么我想您仍然可以使用 URLEncoder
对 URL 进行编码。
String encodedUrl = URLEncoder.encode(url, "UTF-8");
// Then use encodedUrl as you were using url.
[已编辑]
..或者只是将其视为字符串
。很简单,不是吗?
// Please refactor.
String[] paramPart = url.split("?");
String[] params = paramPart[1].split("&");
Map<String, String> paraMap = new HashMap<>();
for(int i=0; i<params.length; i++) {
String[] keyValue;
if(params[i].contains("=")) {
keyValue = params[i].split("=");
paraMap.put(keyValue[0], keyValue[1]);
} else {
params[i-1] = params[i-1] + "&" + params[i];
keyValue = params[i-1].split("=");
paraMap.put(keyValue[0], keyValue[1]);
}
}
关于java - servlet 请求参数值包含& 符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18779631/