Building a Java servlet framework
using reflection, Part 2 - JavaWorld February 2000
Tutorial Details:
Building a Java servlet framework using reflection, Part 2
Building a Java servlet framework using reflection, Part 2
By: By Michael Cymerman
Gain greater functionality with less code using these reflective code samples
hen 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.
Building a Java servlet framework using reflection: Read the whole series!
Part 1. Reflective code provides more functionality in fewer lines of code
Part 2. Gain greater functionality with less code using these reflective code samples
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 Name
Field Type
Mandatory?
First Name
Text
Yes
Last Name
Text
No
Email Address
Email
Yes
City
Text
Yes
State
State
No
Country
Text
Yes
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
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Building a Java servlet framework
using reflection, Part 2 - JavaWorld February 2000
View Tutorial: Building a Java servlet framework
using reflection, Part 2 - JavaWorld February 2000
Related
Tutorials:
Untangle your servlet code with
reflection
Untangle your servlet code with
reflection |
Reflection
vs. code generation
Reflection
vs. code generation |
Java security evolution
and concepts, Part 5
Java security evolution
and concepts, Part 5 |
Boost Struts with
Boost Struts with XSLT and XML |
Rumble in the
jungle: J2EE versus .Net, Part
1
Rumble in the
jungle: J2EE versus .Net, Part
1 |
Sun boosts
Sun boosts enterprise Java |
Axis-orizing objects for SOAP
Axis-orizing objects for SOAP |
The Java Web Services Tutorial
This tutorial is a beginner\'s guide to developing Web services and Web applications using the Java Web Services Developer Pack (Java WSDP). |
Add concurrent processing with message-driven beans
Add concurrent processing with message-driven beans |
Introduction to JavaServer Faces
This article is meant to acquaint the reader with JavaServer Faces, commonly known as JSF. JSF technology simplifies building the user interface for web applications. It does this by providing a higher-level framework for working with your web app, repres |
Java programming dynamics, Part 7: Bytecode engineering with BCEL
Java programming dynamics, Part 7: Bytecode engineering with BCEL
Apache BCEL lets you get to the details of JVM assembler language for classworking
The Apache Byte Code Engineering Library (BCEL) lets you dig into the bytecode of Java classes. You |
Practical Reflection: an excerpt from Hardcore Java
Practical Reflection: an excerpt from Hardcore Java
In this chapter from Hardcore Java, "Practical Reflection," Robert Simmons Jr. writes: "Reflection is one of the least understood aspects of Java, but also one of the most powerful. Reflection is used i |
Mandarax
Mandarax is an open source java class library for deduction rules. It provides an infrastructure for defining, managing and querying rule bases. |
Java Servlets: Design Issues
This article covers the principal concepts associated with servlets. This article examines some of the design issues, and offers some guidelines on the applicability of Java servlets for web based application development. |
JSP (JavaServer Pages) is a standard for combining Java and HTML to provide dynamic content in web pages.
With JSP, you embed Java code in HTML using special JSP tags similar to HTML tags. You install the JSP page, which has a .jsp extension, into the WebLogic Server document root, just as you would a static HTML page. When WebLogic Server serves a JSP page.. |
The JavaTM Web Services Tutorial
A beginner's guide to developing Web services and Web applications on the Java Web Services Developer Pack |
Struts, JavaServer Faces, and Java Studio Creator:
The Evolution of Web Application Frameworks Sun Microsystems' Craig McClanahan, the creator of the Apache Struts Framework, co-specification lead for JavaServer Faces 1.0, and prime architect for Sun Java Studio Creator's new release, explains all three. |
What is Persistence Framework?
What is Persistence Framework?
What is Persistence Framework?
A persistence framework moves the program data in its most natural form (in memory objects) to and from a permanent data store the database. The persistence framework manages the |
Open Source Web Frameworks in Java
Open Source Web Frameworks in Java
Open Source Web Frameworks in Java
Struts
Struts Frame work is the implementation of Model-View-Controller (MVC) design pattern for the JSP. Struts is maintained as a part of Apache Jakarta project and is open |
Understanding Struts Controller
Understanding Struts Controller
Understanding Struts Controller
In this section I will describe you the Controller part of the Struts Framework. I will show you how to configure the struts-config.xml file to map the request to some destination |
|
|
|