Building a Java servlet framework using reflection, Part 2

Gain greater functionality with less code using these reflective code samples

When most developers see the word framework in this article's title, they will immediately become skeptical. I have read numerous articles that purport to describe the one-and-only best solution for Java programming -- especially on the server side. I'm not going to claim that the method outlined here is the only way to go; I merely want to show that it has been successful.

TEXTBOX: TEXTBOX_HEAD: Building a Java servlet framework using reflection: Read the whole series!

:END_TEXTBOX

In Part 1, I outlined a simple scheme through which you could use reflection in the development life cycle to reduce coding time and interdependencies. In this article, I hope to bring that high-level discussion down to specific code examples that you can use in your development projects.

It is important to note that not all applications will benefit from the same level of framework development. Because some applications require more enhanced data access or accept user input differently, some of this information will not be relevant to all of them -- especially those apps whose underlying business processes are in a constant state of flux.

The examples in this article will concern the development of:

  • Dynamically loaded business objects containing developed validation schemes
  • An error-handling hierarchy that will let you concentrate on your specific cases rather than the protection of an entire system
  • Database code that will let you interact with a database simply and efficiently
  • Presentation objects that enable you to concentrate on the logic behind the code rather than presentation mechanics

I hope you will find this article helpful. These principles have enabled my teams to develop complex systems in a short timeframe.

Recap

In Part 1, I divided a system into the three logical layers: business, data, and presentation. I will expand on each of these layers in the following sections. In addition, I'll present some error-handling code that fits into this framework.

Business objects

A business object is associated with each behavior of an application. For example, all objects built to handle forms in an application will have the behaviors of validating input, processing input, interfacing with the data access layer, and presenting output to the user. In a similar fashion, all business objects for pages reached through direct HTML links could have the behavior of analyzing the path taken by the user, data access, and output presentation.

The business object lets you concentrate on the functionality associated with each business use case, such as registering a user or buying an airline ticket. Using this scheme, you can develop business objects with decreased dependencies on the presentation layer, allowing them to undergo strenuous unit testing that is independent of the graphical interface.

Developing business objects and validation

You can load a business object reflectively, based upon the action type passed to the proxy servlet. The action type can be passed as an input parameter, a directory within the URL, or through some alias. This is left to the reader for further investigation.

Once the action type is identified, the business object can be instantiated. The proxy servlet can initialize the business object as follows:

try{
    businessObject.init( ... );
} catch (ExampleException e){
    exceptionHandler.handleException( e);
}

In Part 1 of this series, I demonstrated that you could create these business objects by searching for classes related to the action name that is attached to the page using reflection. Let's assume I've already created a business object for this example.

The BusinessObject interface defines an init method. This method takes a Hashtable of the input parameters passed to the servlet. Using this Hashtable, the business object can retrieve the data from the servlet without relying on the HttpServletRequest object, thereby reducing the dependency on the deployment platform.

You can develop a hierarchy of business objects to create greater functionality with less code. Because the proxy servlet uses the Class object's forName method to find the business object, no logic is needed to keep track of which business object to load. In other words, you don't need to write code that analyzes the action name and determines whether or not that name is associated to a form or a page.

So, you can invoke the RegisterUser business logic through the action RegisterUser. Your application need not understand that this was achieved through a link -- it is performed implicitly through reflection. In fact, a one-to-one correlation between business logic and action is not necessary, depending on the required business rules.

My example application will process user input through a form and display report output to the user. I've developed some simple objects to present this simple framework. Their names and behaviors are shown below:

  • DefaultBusinessObject

    :

    • Validates user input
    • Processes input
    • Present output
  • ReportBusinessObjectextends DefaultBusinessObject
    • Queries database
    • Displays output to the user

For now, I'll assume that BusinessServices has loaded the proper object. I'll elaborate on how to load these objects when I develop the exception handling below. For now, the key is to understand BusinessRules and how you can use them to achieve a high degree of functionality without a lot of coding.

I'll use a registration page to illustrate the benefits of using this framework to handle business rules. Let's assume that the registration page has six fields with the following properties:

Field NameField TypeMandatory?
First NameTextYes
Last NameTextNo
Email AddressEmailYes
CityTextYes
StateStateNo
CountryTextYes

You can write a business object that validates the fields on the page and ensures that they satisfy the business rules associated with the registration action. In this case, three different objects can handle the validation: the email validator, the text validator, and the state validator. These three validation objects are linked into the framework using reflection. The business object will reflectively load each validator as called for in the property table above. This will ensure that the fields are validated properly without requiring the business object developer to hardcode the fields present on a given form page. The power of this reflective approach lies in the fact that a single business object can perform the validation for many, if not all, of the pages in the application. This reduces the development and testing time because the validation code is effectively isolated from the application.

This is a simple example that demonstrates how the framework can handle business rules reflectively. A more complex example would include the validation of groups of interrelated fields, such as a Credit Card group with card number and expiration date fields. These group validation objects can also fit into the proposed framework by adding additional fields to the property tables.

You can use different mechanisms to load the business rules into the framework. One simple scheme involves the use of a static class called BusinessRules. This class will load and store all the business rules so that they can be referenced by the application as static variables. Here's an example:

// initialization of the hashtable
public static Hashtable hRegisterUserRules = new Hashtable();
// a lookup value to enter/find the field names 
// - makes the interface cleaner to use.
public static final String sFirstName = "FirstName";
static {
    // create a rule object
    Rule rule = new Rule();
    // set the validation
    Rule.setValidation(Rule.TEXT);
      // indicate whether or not the field is required
      Rule.setMandatory(true);
    
    // add the rule to the hashtable with the fieldname as the key
      hRegisterUserRules.put(sFirstName, rule);
}

This is one example of loading the rules from a static class. A more developed framework could load the rules from a properties file or database, thereby providing the development team with a more flexible means to modify the behavior of the application.

Let's assume that the other fields from the RegisterUser action have been entered into the BusinessRules class as shown above. We can now go on to discuss the reusable validation mechanism proposed for this framework. That validation would be contained in the BusinessObject, which contains a protected method called isValid. This method is responsible for coordinating the loading of the BusinessRules associated with the action being performed and ensuring that the fields passed by the user conform to those rules.

At this point, the development team must choose how it will handle multiple-paged input forms. Should a single action for each page be assumed, or should actions be able to span across pages? In the example I've described here, there is no limitation on the location of fields on one form or another. The data object will catch any missing fields when attempting to write the results to the database. This gives the team developing the business objects complete flexibility in the user interface design.

Having made that design decision, I'll illustrate how you can find the BusinessRules object using reflection. What follows is a simple code fragment that illustrates the reflective loading of a class variable as an object rather than a set of values.

private Hashtable loadBusinessRules(String sActionRules) throws UnexpectedException
{
// Initialize the rules table to null
    Hashtable rulesTable = null;
    try {
        // Load the BusinessRules Class using the static variable 
            // containing the fully qualified path value.
        Class c = Class.forName( BusinessRules.BUSINESSRULES);
        // --- Get the hashtable based upon the action name ---//
// --- (using reflection) --- //
        // The loaded class (BusinessRules) has a field such as 
            // RegisterUserRules that we try to load.
        // If the load is successful, 
            // we call get(null) to load the actual object rather than the value
        // We cast the value as a Hashtable and return it to the user.
        rulesTable = (Hashtable) c.getField(sActionRules).get(null);
    } catch (Exception e) {
        // The hashtable was not found.  All actions will have some form of
        // rule interface.
        throw new UnexpectedException(
                 "No business rules exist for this Action," + sActionRules);
    }
    return rulesTable;
}

In this case, you're loading the entire Hashtable from the BusinessRules class. This will allow you to use the methods contained within the Hashtable object to perform validation.

Here's a code sample from the isValid method, illustrating how the validation might be performed:

1 2 3 Page 1
Page 1 of 3