Java servlet : request.getParameter() returns a parameter from the query string in a POST request

10,698

Check the javadoc for the getParameter method:

https://tomcat.apache.org/tomcat-7.0-doc/servletapi/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29

Like it is stated, you are sending 2 parameters on the request with the same name, one from the query string and another on the body.

Now it is up to you to either validate that no parameter is coming from the query string or read directly values from the request body.

Share:
10,698
Nico
Author by

Nico

Updated on June 04, 2022

Comments

  • Nico
    Nico almost 2 years

    I'm currently developing a Servlet that runs under Glassfish 4. I implemented the doPost() method and I need to ensure that the parameters are passed using the POST body, and not in the query string.

    I wrote a test implementation to check it:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        String name = request.getParameter("name");
    
        response.getOutputStream().print(name);
    }
    

    If I call my page with POST with this url:

    http://localhost:8080/myservlet/testservlet
    

    and pass name=Nico into the post body, the value Nico is returned, and it's okay.

    Now if I call it this way:

    http://localhost:8080/myservlet/testservlet?name=Robert
    

    and I still pass name=Nico in the POST body, Robert is returned, and the name=Nico is ignored.

    I just would like to avoid parameters to be passed in the URL.
    Is there a way to explicitly retrieve parameters from the POST body instead of body + query string?

  • Nico
    Nico almost 10 years
    Hi all, and thank you for your time. Well, I expected something like php's $_POST and $_GET. Finally the getParameter() method acts more like php's $_REQUEST. Well I'll mark @hvieira's answer as good because the link provided explains my problem (although it doesn't solve it) and the suggestion to process the raw response body fits good for the question I asked. Anyway, thanks all for your comments! And finally you're right, there's no need to wonder where the parameter comes from... I was just focused on PHP's $_POST and $_GET arrays. Nico