使用Java Servlet关联数组请求参数解析 [英] Associative array request parameter parsing with Java Servlet
问题描述
是否可以使用Java servlet API解析诸如此类的请求中的字符串键?
Is it possible to parse the string keys from a request such as this, with the Java servlet API?
http://localhost:8080/?assocArray[key1]=value1&assocArray[key2]=value2&assocArray[key3]=value3
getParameterValues("assocArray") returns ["value3","value1","value1"]
返回数组中值的顺序不是键的顺序(无关紧要)
The ordering of the values in the returned array is not order of the keys (not that it matters)
已解决:可能将键解释为简单的全局键字符串.Java无法将它们识别为数组.使用正则表达式
SOLVED: It is possible, the keys are interpreted as simple global key strings. Java doesn't recognize them as an array. Use regex
推荐答案
不直接. []
在HTTP请求参数中没有特殊含义,并且Servlet API不能将其识别为数组键(您可能是PHP程序员,确实有专有的解析器吗?).您需要循环分析并自己收集它.
Not directly. The []
have no special meaning in HTTP request parameters and are by the Servlet API not recognized as array keys (you was perhaps a PHP programmer which indeed has a proprietary parser for this?). You need to parse and collect it yourself in a loop.
例如
Map<String, String> assocArray = new LinkedHashMap<String, String>();
for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
String name = entry.getKey();
if (name.startsWith("assocArray[")) {
String key = name.substring(name.indexOf('[') + 1, name.indexOf(']'));
assocArray.put(key, entry.getValue()[0]);
}
}
这篇关于使用Java Servlet关联数组请求参数解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!