Jonathon
Jonathon

Reputation: 16283

Java Servlets: Differentiate between GET and POST

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.

To illustrate, using PHP these values are provided through the $_GET and $_POST superglobals.

Upvotes: 2

Views: 1269

Answers (1)

user2023577
user2023577

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

Related Questions