Introduction

Handling data from HTML forms is a common task facing web developers. Typically this results in a lot of boilerplate code checking for null values and empty strings, for example

String username = req.getParameter("username");

if(username != null && !username.trim().equals("")) {
    // do
}

Or if a value needs to be parsed into a number:

int userId;

try {
   userId = Integer.parseInt(req.getParameter("userId"));
}
catch(NumberFormatException e) {
    // handle
}

jReform offers a simple solution for validating forms with very few lines of code and without any XML files.

Creating a form

A form is defined as an object extending the HtmlForm class. This base class contains methods for adding inputs to the form and validating its values. For example, a form with fields username and userId will look as follows:

public class SimpleForm extends HtmlForm {

    public UserProfileForm() {
        input(stringType(), "username");
        input(intType(), "userId");
    }
}

Input names refer to the name attribute of an input. The type variables, stringType() and intType(), specify the type that input data should be converted to. jReform will validate that user's input can be converted to the proper type.

<input type="text" name="username">
<input type="text" name="userId">

Validating a form

To validate the form we simply call the validate(HttpServletRequest) method. This method will check that all required values have been given and will be convert those values into specified type. If validation is successful input values can be accessed as follows:

SimpleForm form = new SimpleForm();

if(form.validate(req)) {
    String username = form.getStringValue("username");
    Integer userId = (Integer)form.getValue("userId");
}

To avoid casting and specifying input names each time a value needs to be accessed, add get methods to the form class. The compete form class will therefore looks as follows:

public class SimpleForm extends HtmlForm {

    public UserProfileForm() {
        input(stringType(), "username");
        input(intType(), "userId");
    }

    public Input getUsername() {
        return getInput("username");
    }
    
    public Input getUserId() {
        return getInput("userId");
    }
}

This makes the servlet code even more readable:

String username = form.getUsername().getValue();
Integer userId = form.getUserId().getValue();

The getters can also help improve the JSP page. The hard-coded input names can be removed which reduces the scope for errors.

<input type="text" name="${form.username.inputName}">
<input type="text" name="${form.userId.inputName}">

More information

More detailed examples of how to use jReform (with downloadable source code) can be found here. There is also a section describing main features of the framework.