Reputation: 16283
Is there a reliable way to separately extract GET
and POST
parameters using a HttpServletRequest
?
That is, differentiate parameters that were sent in the query string (GET
) to parameters that were sent in the request body (POST
), assuming Content-Type: application/x-www-form-urlencoded
.
Example
POST /path HTTP/1.1
Host: test.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 42
first_name=posted_foo&last_name=posted_bar
I would like to end up with two variables, one containing the values from the URL and one containing the values from the request body:
get = {"first_name": "foo", "last_name": "bar"}
post = {"first_name": "posted_foo", "last_name": "posted_bar"}
The only methods I seem to be able to extract these parameters are the getParameter*
methods.
HttpServletRequest.getParameter
: Returns a single string and tends to be the value provided in the URL (GET).HttpServletRequest.getParameterValues
: Returns an array of strings containing all of the values provided in the query string and request body. Those passed via the query string tend to appear first. However, if only one value is present in the returns array of strings, it cannot be reliably determined whether the value came from the query string or the request body.To illustrate, using PHP these values are provided through the $_GET
and $_POST
superglobals.
Upvotes: 2
Views: 1269
Reputation: 2083
The query string is trivial to parse, thus gives you the URI query param names, while the getParameterNames() gives you the whole set.
Split the query string by '&', then subsplit each token by '='. For each key and value, perform the URLDecoder.decode(). That's all.
Toss all such keys in a set. If the param is in the uri query set it a good chance it's only there. If you must find if it is also in the post, actually, post form-encoded data is also coded like that, but that post is consumed so it's too late. Besides, the post could also be a multipart encoding which is non-trivial decode.
In the end, it's odd that you need this distinction. Can you explain for what purpose you seek this distinction?
Upvotes: 1