0

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?

1
  • Is it safe to rely on the query string order ? Is there any guarantee of the order a browser will choose? Can the order change if cosmetic changes are made to the form? Commented Jul 24, 2014 at 8:21

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

@bayou.io How do I go about decoding the key/value pairs?
@Braj I don't really need all the other params, I just need the first one, so is it safe to just find the first "&" and cut the string from there? Or do I need to worry about "&" as an encoded character?
@kerafill you don't need to worry about "&" because that is already decoded. for more info follow the link.
we need to parse the query first by & and =, then decode the name and value. because the name/value could contain encoded & or =
@Braj OK! Works great! I used your code example, but assigned the values instead of println! ^_^
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.