aprogrammer
aprogrammer

Reputation: 1774

Servlet get GET and POST's parameters at the doPost method

My problem is when I'm trying to access a POST Variable with request.getParameter("name"), it works perfectly. But in some conditions, when a POST request arrives at my application, I also need to get GET Parameter from the Query String.

As far as I can see, with getParameter, you can only access current request's parameters, but, as in my condition, as I said, I also need to fetch GET Parameters inside doPost method.

Is there a way to fetch GET Parameters without parsing the Query String?

Upvotes: 1

Views: 11279

Answers (4)

Simon the Salmon
Simon the Salmon

Reputation: 302

To complete @Rei answer check out this code :

your form

<form action="?nom=nom1">
<input type="hidden" name="nom" value="nm2"/>

your doPost

System.out.println(request.getParameter("nom"));
        
String s = "";
for(String ss : request.getParameterValues("nom")) {
    s += "|" + ss;
}
System.out.println(s);
System.out.println(request.getParameterMap().get("nom"));

what will be printed

nom1
|nom1|nm2
[Ljava.lang.String;@c7068db

ps : thanks to Julien for the code and testing

Upvotes: 0

Faraz
Faraz

Reputation: 6265

I think you have a confusion here. You can retrieve all the request parameters (in both GET or POST or others) using the same getParameter(..) depending upon the type of request. If it's a GET request, you can retrieve all the GET parameters.

If it's a POST request, you can retrieve all the POST parameters. You get parameters using getParameter(...). And you make one request at a time. If you make a POST request in html or JSP file, you use doPost method receive all the parameters. At this point, there is nothing in GET request. Then after that, you make a GET request, you retrieve all the parameters in doGet method. At this moment, there is nothing in POST. Remember, HTTP requests are stateless.

Upvotes: 1

Rei
Rei

Reputation: 6353

If you have parameters with the same name in the query string and in the posted form data, use getParameterValues().

Example:-

String fromQuery = request.getParameterValues("name")[0];
String fromForm = request.getParameterValues("name")[1];

Upvotes: 3

Gurwinder Singh
Gurwinder Singh

Reputation: 39457

The getParameter() method can return (if possible) both GET and POST parameters as it works transparently between GET and POST. You don't need to do any explicit work to get the GET parameters. you can use getParameter for both query parameters and POST parameters.

But should you do it? - It's considered a poor design practice especially if there is sensitive information to be sent.

Take a look at this answer:

Upvotes: 1

Related Questions