问题
I have below the url.
http://localhost:8080/servlet?user=John&message=hai&hello&recipient=scott
In above url i have 3 request parameters as below.
user=John
message=hai&hello
recipient=scott
Here the problem is with message
request parameter's value.because here its value contains ampersend (&). when i try request.getParameter("message")
then i get only hai
but not hai&hello
. How can i solve this issue?
Thanks!
回答1:
Try this, instead ....&message=hi%26hello....
. I mean, encode it.
[Edited]
As you said you have no control over it, and it is legacy application and they cannot fix it; then you can still, I suppose, use URLEncoder
to encode the URL.
String encodedUrl = URLEncoder.encode(url, "UTF-8");
// Then use encodedUrl as you were using url.
[Edited]
..or just treat it as a String
. Simple, isn't it?
// 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]);
}
}
回答2:
If you are sure that &recipient
always comes after &message
or that &message
may come as last parameter or you know the set of possible parameters, then you will need the get the query string from the request and try to split it accordingly.
For example if &recipient
alway comes after &message
then you could do (pseudo code / untested):
int s = queryString.indexOf("&message");
int e = queryString.indexOf("&recipient");
String messageValue = queryString.substring(s + "&message".length(), e);
来源:https://stackoverflow.com/questions/18779631/servelt-request-parameter-value-contains-ampersand