When can a parameter value be null?

I’ve noticed that request.getParameter() always return a string for the parameter that corresponds to a text field in my form, even when the field is empty. To find out if the field is empty, I need to use code like this:

if (request.getParameter("foo").length() == 0) {
  ...
}

But in your book, you have examples where you test if the parameter value is null instead.

When is the value null and when is it an empty string?

Answer:
Most (all?) browers send empty form text fields to the server as an HTTP request parameter with an empty value. Hence, the value for a text field will rarely be null. Typically it’s an empty string. But it never hurts to test for both null and empty string to be on the safe side:

String foo = request.getParameter("foo");
if (foo == null || foo.trim().length() == 0) {
  ...
}

For checkboxes, radio buttons and select lists, on the other hand, the browser only sends a parameter if the item is selected. For these types of form elements, you must always be prepared to handle a null value.

Leave a Reply

Your email address will not be published. Required fields are marked *