简体   繁体   English

如何在java中有效解析查询参数?

[英]How to parse query param effectively in java?

All I have is the request URI from which I have to parse the query params.我所拥有的只是请求 URI,我必须从中解析查询参数。 What I'm doing is adding them to json/hashmap and fetching again like the following我正在做的是将它们添加到 json/hashmap 并再次获取,如下所示

String requestUri = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";

All I have to do is to finally assign it to variables like the following我所要做的就是最终将它分配给如下变量

String name = "raju";
String school = "abcd";
String college = "mnop";
String color = "black";
String fruit = "mango";

So I am parsing the request uri like the following所以我正在解析请求 uri,如下所示

String[] paramsKV = requestUri.split("&");
JSONArray jsonKVArr = new JSONArray();
for (String params : paramsKV) {
    String[] tempArr = params.split("=");
    if(tempArr.length>1) {
        String key = tempArr[0];
        String value = tempArr[1];
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(key, value);
        jsonKVArr.put(jsonObj);
     }
 }

The another way is to populate the same in hash map and obtain the same.另一种方法是在哈希映射中填充相同的内容并获得相同的内容。 The other way is to match the requestUri string with regex pattern and obtain the results.另一种方式是将requestUri字符串与正则表达式匹配并获得结果。

Say for an example to get the value of school I have to match the values between the starting point of the string school and the next & - which doesn't sound good.举个例子来获取school的值,我必须匹配字符串school的起点和下一个&之间的值——这听起来不太好。

  1. What is the better approach to parse the query String in java?在 java 中解析查询字符串的更好方法是什么?
  2. How could i handle the following thing in a better way?我怎样才能更好地处理以下事情?

I need to construct another hash map like the following from the above results like我需要从上面的结果中构建另一个哈希映射,如下所示

Map<String, String> resultMap = new HashMap<String, String>;

resultMap.put("empname", name);
resultMap.put("rschool", school);
resultMap.put("empcollege", college);
resultMap.put("favcolor", color);
resultMap.put("favfruit", fruit);

To make it simple all I have to do is to parse the query param and construct a hashMap by naming the key filed differently.为了简单起见,我所要做的就是解析查询参数并通过以不同方式命名key来构造一个 hashMap。 How could I do it in a simple way?我怎么能以简单的方式做到这一点? Any help in this is much appreciated.非常感谢这方面的任何帮助。

Short answer: Every HTTP Client library will do this for you.简短回答:每个 HTTP 客户端库都会为你做这件事。

Example: Apache HttpClient's URLEncodedUtils class示例:Apache HttpClient 的URLEncodedUtils

String queryComponent = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
List<NameValuePair> params = URLEncodedUtils.parse(queryComponent, Charset.forName("UTF-8"));

They're basically approaching it the same way.他们基本上以同样的方式接近它。 Parameter key-value pairs are delimited by & and the keys from the values by = so String's split is appropriate for both.参数键值对由&分隔,值中的键由=分隔,因此 String 的split适用于两者。

From what I can tell however your hashmap inserts are mapping new keys to the existing values so there's really no optimization, save maybe for moving to a Java 8 Stream for readability/maintenance and/or discarding the initial jsonArray and mapping straight to the hashmap.据我所知,您的 hashmap 插入正在将新键映射到现有值,因此实际上没有优化,可能除了为了可读性/维护而移动到 Java 8 Stream 和/或丢弃初始 jsonArray 并直接映射到 hashmap 之外。

Here is another possible solution:这是另一种可能的解决方案:

    Pattern pat = Pattern.compile("([^&=]+)=([^&]*)");
    Matcher matcher = pat.matcher(requestUri);
    Map<String,String> map = new HashMap<>();
    while (matcher.find()) {
        map.put(matcher.group(1), matcher.group(2));
    }
    System.out.println(map);

You can use Java 8 and store your data in HashMap in one operation.您可以使用 Java 8 并通过一次操作将数据存储在 HashMap 中。

Map<String,String> map = Pattern.compile("\\s*&\\s*")
                .splitAsStream(requestUri.trim())
                .map(s -> s.split("=", 2))
                .collect(Collectors.toMap(a -> a[0], a -> a.length > 1 ? a[1]: ""));

You can do it by Jersey library ( com.sun.jersey.api.uri.UriComponent or org.glassfish.jersey.uri.UriComponent class):您可以通过 Jersey 库( com.sun.jersey.api.uri.UriComponentorg.glassfish.jersey.uri.UriComponent类)来完成:

String queryComponent = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
MultivaluedMap<String, String> params = UriComponent.decodeQuery(queryComponent, true);

Use jackson json parser.使用杰克逊 json 解析器。 Maven dependency: Maven 依赖项:

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.3</version>
        </dependency>

Now use ObjectMapper to create Map from json string:现在使用 ObjectMapper 从 json 字符串创建地图:

ObjectMapper mapper = new ObjectMapper();
Map list = mapper.readValue(requestUri, Map.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM