简体   繁体   English

如何在Java Servlet中读取查询字符串中的第一个键/值对?

[英]How to read first key/value pair in a query string in java servlets?

I have this servlet that accepts dynamic parameter names in the query string, but the query string is also appended other parameters by some javascript plugin. 我有这个servlet,可以在查询字符串中接受动态参数名称,但是查询字符串还通过一些javascript插件附加了其他参数。

Here's the request scenario: 这是请求方案:

http://foo.com/servlet?[dynamic param]=[param value]&[other params]=[other values]...

I'd like to be able to read the first parameter, so then the servlet will carry out its execution depending on the dynamic param name, or do nothing if it doesn't recognize the param name. 我希望能够读取第一个参数,因此servlet将根据动态参数名称执行其执行,如果无法识别参数名称,则不执行任何操作。 I'm 100% certain that the first param name is always the dynamic one, because I control the query string construction thru an ajax call. 我100%确信第一个参数名称始终是动态名称,因为我通过ajax调用来控制查询字符串的构造。

The problem I've encountered is that HttpRequestServlet.getParameterMap() or .getParameterNames() ordering doesn't always correspond to the query string order, so the servlet does nothing half/most of the time depending on the frequency of parameters. 我遇到的问题是HttpRequestServlet.getParameterMap().getParameterNames()排序并不总是与查询字符串的顺序相对应,因此,根据参数的频率,servlet在一半/大部分时间内不执行任何操作。

How do I always read the first param in a query string? 如何始终读取查询字符串中的第一个参数?

You can use HttpServletRequest#getQueryString() then split the values based on & and get the first pair of query param name-value then split it based on = 您可以使用HttpServletRequest#getQueryString(),然后基于&拆分值&并获取第一对查询参数名称-值,然后基于=拆分

sample code: 样例代码:

String[] parameters = URLDecoder.decode(request.getQueryString(), "UTF-8").split("&");
if (parameters.length > 0) {
    String firstPair = parameters[0];
    String[] nameValue = firstPair.split("=");
    System.out.println("Name:" + nameValue[0] + " value:" + nameValue[1]);
}

Read more about URL decoding 阅读有关URL解码的更多信息

You can change that URL to read something like 您可以更改该网址以读取如下内容

http://foo.com/servlet/dynamicParam/paramValue/?otherParam=otherValue

This URL structure better conforms with HTTP resource's idea and you no longer have a problem where parameter order matters. 该URL结构更好地符合HTTP资源的思想,并且在参数顺序很重要的时候您不再有问题。 The above is pretty easy to do if you use a modern MVC framework. 如果您使用现代MVC框架,则上面的操作非常容易。

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

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