servelt request parameter value contains ampersand?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 12:53:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!