简体   繁体   中英

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.

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. 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.

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.

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 =

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

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. The above is pretty easy to do if you use a modern MVC framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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