Suggested way to encode name/value pairs in the Token of a GWT Activitie's place Token
In GWT using the History/Activities/Places apis you end up with urls like this
http://192.168.0.104:8888/brokerage.html?gwt.codesvr=192.168.0.104:9997#StartPlace:params
Where the word params is the place "token" where parameters can be passed into the StartPlace object. For most of my applications a single string is enough to reload my data with refreshed is pressed. On a few Ac开发者_开发技巧tivities/Places/Pages however I need to split that Place token into a number of name/value pairs.
Does anybody have a suggestion for how to handle this? I am currently writing a class that builds a string out of name/value pairs by separating them in a url fashion using &name=value. It would be great if somebody knew of a class that could handle this or something.
How about simply copy/pasting the code from Window.Location
for the parsing (private method buildListParamMap
; you can also call it using JSNI –which allows bypassing Java visibility– given that it's a static method with no state), and UrlBuilder.buildString
for the serialization?
String parameters="name1=value1&name2=value2&name3=value3";
HashMap<String, String> parameterMap = new HashMap<String, String>();
String[] parameterPairs = parameters.split("&");
for (int i = 0; i < parameterPairs.length; i++) {
String[] nameAndValue = parameterPairs[i].split("=");
parameterMap.put(nameAndValue[0], nameAndValue[1]);
}
....
String name1Value = parameterMap.get("name1");
This is all untested code, and it has unchecked array bounds! Make sure you don't have extraneous '&' or '=' signs, since they'll mess up the parsing.
This is what I came up with, it should work for others. Using a hash map is a good idea, I'll modify my code.
public static String parseNamedParam(String name, String token) {
if (name == null || "".equals(name) || token == null || "".equals(token)) {
return null;
}
final String[] strNameValuePairs = token.split("&");
for (String entry : strNameValuePairs) {
final String[] strNameValuePair = entry.split("=");
final String decodedName = URL.decodeQueryString(strNameValuePair[0]);
if (decodedName.equals(name)) {
return URL.decodeQueryString(strNameValuePair[1]);
}
}
return "";
}
And
public static String generateTokenString(List<TokenParam> tokenParams) {
if (tokenParams == null || tokenParams.isEmpty()) {
return "";
}
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < tokenParams.size(); i++) {
final TokenParam tokenParam = tokenParams.get(i);
final String nameEncoded = URL.encodeQueryString(tokenParam.getName());
final String valueEncoded = URL.encodeQueryString(tokenParam.getValue());
if (i != 0) {
sb.append("&");
}
sb.append(nameEncoded);
sb.append("=");
sb.append(valueEncoded);
}
return sb.toString();
}
精彩评论