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?

kerafill
  • 274
  • 1
  • 4
  • 14
  • 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? – Raedwald Jul 24 '14 at 08:21

2 Answers2

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

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • @bayou.io How do I go about decoding the key/value pairs? – kerafill Jul 23 '14 at 16:25
  • @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 Jul 23 '14 at 16:28
  • 1
    @kerafill you don't need to worry about "&" because that is already decoded. for more info follow the link. – Braj Jul 23 '14 at 16:30
  • 1
    we need to parse the query first by `&` and `=`, then decode the name and value. because the name/value could contain encoded `&` or `=` – ZhongYu Jul 23 '14 at 16:33
  • @Braj OK! Works great! I used your code example, but assigned the values instead of println! ^_^ – kerafill Jul 23 '14 at 16:35
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.

dimoniy
  • 5,820
  • 2
  • 24
  • 22