Reading HTTP request parameters

Even if you're new to web programming, you've probably seen HTTP request parameters. These are the bits sometimes "tacked on" to the end of a URL when you submit a form on a web page. For example, if an HTML form was defined as follows with a username field:

<form action="http://www.examplesite.com/login">
<input type=text name="username">
<input type=submit>
</form>

then submitting the form will make the browser request http://www.examplesite.com/login, but with the username parameter tacked on to the end:

http://www.examplesite.com/login?username=mcjones

When parameters are used

As well as being used for HTML forms as in the above example, HTTP parameters are also used in cases such as:

Essentially, any time a simple, short piece of data needs to be passed from the client to the server, they're a reasonable choice.

Reading parameters from the Servlet

Instead of adding request parameters to the end of the URL, it is also possible to POST them as actual data. To the Servlet, it makes no difference which request method (GET or POST) was used to send the parameters. In either case, we read the parameter using the getParameter() method of HttpServletRequest:

public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
  String userName = req.getParameter("username");
}

If the given parameter was not set, then null was returned. A couple of methods are available to help us enumerate the parameters passed in:

It may sound odd that getParameterMap() returns mappings to arrays of strings. The reason is that strictly speaking, more than one value can be assigned to the same parameter name. (In practice, it is rare to do so.)

Parsing POSTed parameters "manually"

Usually, the most convenient way of reading request parameters is via the getParameter() method. It should be noted that if you use this method to read parameters that are POSTed, you shouldn't generally use the getReader() method to obtain and read the POSTed data "manually".

Parameters vs request headers

HTTP parameters are generally used to pass user-supplied data. They should not be confused with HTTP request headers, which are generally used to carry "meta" information, such as the character encoding, referring page, type of browser etc.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.