102

In HttpServletRequest, getParameterMap returns a Map of all query string parameters and post data parameters.

Is there a way to get a Map of ONLY query string parameters? I'm trying to avoid using getQueryString and parsing out the values.

4
  • 16
    You can have both ... you can have query string parameters on a POST request. And in that case, they are all returned by "getParameterMap" Commented Jul 27, 2011 at 15:51
  • Oh, ok. Why does one need both, just curious? Commented Jul 27, 2011 at 15:55
  • 2
    Because on the resulting page, I want a query string to appear in the url / be in the query string. We have a tracking system which looks for specific parameters in the query string. Commented Jul 27, 2011 at 16:24
  • req.getParameterMap().containsKey("username"); Commented Jul 12, 2016 at 12:42

6 Answers 6

127

You can use request.getQueryString(),if the query string is like

username=james&password=pwd

To get name you can do this

request.getParameter("username"); 
Sign up to request clarification or add additional context in comments.

3 Comments

This is for use un Java Server pages.
the second will spoil request stream, I assume the question is how to get username and keep input stream for later processing
@PavelNiedoba can you expand on the request stream becoming spoiled comment? Why is that?
26

Contrary to what cularis said there can be both in the parameter map.

The best way I see is to proxy the parameterMap and for each parameter retrieval check if queryString contains "&?<parameterName>=".

Note that parameterName needs to be URL encoded before this check can be made, as Qerub pointed out.

That saves you the parsing and still gives you only URL parameters.

5 Comments

Note that parameterName needs to be URL encoded before this check can be made.
The query string never contains ?. That's the separator character between URI and query string.
Hi @DoubleMalt, I have the same requirement, but can't get the solution you provided. Can you provide example code?
@VishalZanzrukia: What is your code that doesn't work?
I like the idea, but there is not always a "=" character in the query string. If parameter value is empty there is only <parameterName> in the query string. I personally think splitting by "&" and "=" would be a better solution.
26

The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.

The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":

GET /persons?age=42

The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":

PUT /persons?age=42

hair=grey

So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.

Comments

19

As the other answers state there is no way getting query string parameters using servlet api.

So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)

I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.

Example: username=james&username=smith&password=pwd1,pwd2 will return

password : [pwd1, pwd2] (length = 2)

username : [james, smith] (length = 2)

public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
    Map<String, String[]> queryParameters = new HashMap<>();
    String queryString = request.getQueryString();
    if (StringUtils.isNotEmpty(queryString)) {
        queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
        String[] parameters = queryString.split("&");
        for (String parameter : parameters) {
            String[] keyValuePair = parameter.split("=");
            String[] values = queryParameters.get(keyValuePair[0]);
            //length is one if no value is available.
            values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
                    ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
            queryParameters.put(keyValuePair[0], values);
        }
    }
    return queryParameters;
}

7 Comments

I consider this much better that accepted answer, don't know why to avoid parsing query string because creating proxy is not better solution
I am just wondering,if any of the query parameters contains & character in its value, whether it will give you the correct result
@amdg - that character would be URL encoded, so that code is good. If it weren't encoded, the string would be unparsable.
Consider using URLDecoder.decode(keyValuePair[0]) (or [1]) as well: docs.oracle.com/javase/6/docs/api/java/net/URLDecoder.html
query params with csv separated values isn't being considered here. for ex: username=james&username=smith&password=pwd1,pwd2 will have a map with 2 values for username (which is correct) but only 1 value for password (which is incorrect)
|
8

Java 8

return Collections.list(httpServletRequest.getParameterNames())
                  .stream()
                  .collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));

1 Comment

httpServletRequest.getParameterMap() suffices.
2

I am afraid there is no way to get the query string parameters parsed separately from the post parameters. BTW the fact that such API absent may mean that probably you should check your design. Why are you using query string when sending POST? If you really want to send more data into URL use REST-like convention, e.g. instead of sending

http://mycompany.com/myapp/myservlet?first=11&second=22

say:

http://mycompany.com/myapp/myservlet/11/22

3 Comments

I'm using query string parameter in a POST because i want to maintain any and all query strings passed to the original form through the POST. This is primarily for tracking purposes... i'm not sure that the REST-like convention would work in this case, because I'm pretty sure the tracking library looks for specific parameters in the query string.
Any reason in particular that you would recommend using the REST-like convention to a query string parameter? Not sure I understand what the advantage is?
"BTW the fact that such API absent may mean that probably you should check your design." In this case it means Oracle should check their design :)

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.