Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Strut your stuff with JSP tags

Use and extend the open source Struts JSP tag library

  • Print
  • Feedback
One great benefit of JSP and J2EE is that they enable the developer community to speak a common language. The downside of those technologies is that they sometimes require a lot of mindless coding more suitable for a machine than a human being. That is particularly true in today's big e-commerce projects with their huge teams and tight deadlines. In such situations everyone reverts to simple and safe procedures -- the most advanced form of reuse being cut and paste. There is simply no time for experimentation. Fortunately, JSP allows more advanced forms of reuse to be imported from third parties in the form of custom tag libraries. This article focuses on one such library, the open source Struts tag library, and presents extensions that ease your coding effort.

The Struts package, which is part of the open source Jakarta project, provides a well-thought-out MVC (model-view-controller) framework that many projects would do well in adapting at the start of their Website development. The custom tags represent the view part of that framework, but it is perfectly feasible to use the tags without the model and controller part.

Most of the tags defined by Struts help associate bean properties with form fields. That greatly reduces the complexity of writing forms that remember all user choices between requests. That is particularly true for complex tags such as the standard select tag, in which plain JSP code to restore the user's choice can get quite bulky.

Even with Struts's custom tags there remain two time-consuming and tedious tasks you must do for the page bean: you must write properties that hold the user input between requests and implement user input validation and error message display. This article presents techniques to deal with those tasks. The use of automatic properties alleviates the creation of all page bean properties that primarily serve to remember user input when the page has to be redisplayed, either because it had errors or because the user wanted to review a previous step in a multipage transaction. Validation with regular expressions greatly simplifies the validation of user input and the display of appropriate error messages. The amount of code needed to implement those techniques is surprisingly small and can be found in the code listings in this article.

The following image shows a page that uses both techniques:

Figure 1. Webpage using both automatic properties and validation with regular expressions (40 KB)



Listing 1 shows the JSP behind this form. Some table and font formatting has been removed for clarity, so the page would look a bit jagged and less colorful but otherwise just like the above figure.

Listing 1. transfer.jsp: The transfer form

<%@ taglib uri="/WEB-INF/struts.tld" prefix="struts" %>
<jsp:useBean id="transfer" scope="session" class="com.bank.PageBean"/>
<%
    org.apache.struts.util.BeanUtils.populate(transfer, request);
    if(request.getParameter("marker") == null)
        // initialize a pseudo-property
        transfer.set("days", java.util.Arrays.asList(
            new String[] {"1", "2", "3", "4", "31"}));
    else 
        if(transfer.validate(request))
            %><jsp:forward page="transferConfirm.jsp"/><%
%>
<html>
<head>
<title>MyBank - Transfer</title>
</head>
<body>
    <H2> Money Transfer </H2>
    <struts:form name="transfer" type="com.bank.PageBean"
               action="transfer.jsp" method="post">
        <struts:hidden property="marker"/>
         Receiver:
        <struts:text property="receiver" pattern="@personName"
                           errorMessage="@personName"/>
        <%= transfer.getError("receiver") %><br>
        Account:
        <struts:text property="destAccount" pattern="/^[0-9]{7,9}$/"
                           errorMessage="Account can have 7 and 9 digits"/>
        <%= transfer.getError("destAccount") %><br>
        Amount:
        <struts:text property="amount" pattern="@amount"
                           errorMessage="Amount can have 8 digits plus two decimals" />
        <%= transfer.getError("amount") %><br>
        Date:
        <struts:select property="day">
        <struts:options property="days"/>
        </struts:select><br>
        <struts:submit value="submit"/>
    </struts:form>
</body>
</html>


The page bean, specified in the useBean tag and in the Struts form tag, is completely generic. It knows nothing about that particular form, neither the names of the fields nor the constraints on their contents. All that information comes from the JSP page. In many cases, though, the basic bean would be extended to, for example, communicate with the back end, perhaps through JDBC, CORBA, or EJBs.

Let's take a short walk through the JSP code in Listing 1. First the taglib tag at the top says where to find a file describing the syntax of any tags prefixed with "struts:". Then the useBean tag creates a scripting variable named "transfer" of class PageBean and associates it with any previously used bean of the same name, class, and scope. If no such bean exists, then it is created.

Next you see a scriptlet that represents the controller code for that page. Having the controller code on the JSP page goes against the separation of code and content but helps keep this example short. The form on the page thus uses the page itself as a target, so this same page will be called when the form is submitted.

The scriptlet starts by populating the bean properties with the request data (if any). Then the presence of the marker parameter is used to detect if that is the initial page request or a subsequent form submit request. If that is the initial request, the days property for the options tag is initialized. If, on the other hand, that is a subsequent submission of the form, then a validation function is called and, if it succeeds, control is forwarded to the next page in the transaction.

The Struts tags are next. The form tag specifies that the transfer bean is where all the enclosed field tags should look for properties. Each of the three text tags specifies which transfer property should be used for initialization, to which regular expression pattern the user's input should be compared, and what should be displayed if the input doesn't match the pattern. A pattern or an error message starting with "@" denotes a predefined string. If the users input fails to match the pattern, the expressions

<%= transfer.getError(fieldname) %>


will display the error messages when the page is redisplayed for correction. Finally, the select tag lets the user select any item in the list specified in the options tag. The initial selection is the value of the day property, which also receives the value that the user selects.

Let's now examine the changes you need to make to the Struts library for that to work.

Automatic properties

Automatic properties are to JSP what dynamic variables are to a programming language. In a programming language that supports them, you can use dynamic variables without declaring them first. Similarly, you can use automatic properties on a JSP page without defining them with set and get methods. Automatic properties are not really properties in the Java sense, but they serve the same purpose as properties in JSP pages. They reduce the need for the tiresome triad of a getter, setter, and member variable to code a property that corresponds to a form field. Instead, those entries are created automatically based on the request. The Struts tags, with the modifications made here, will then treat that data as properties. If initialization is required before the page is first sent to the user, you can initialize in a constructor, in the bean's initialization block or, as in the example above, directly in the JSP. That last approach, however, mixes code and content, and it isn't generally recommended.

  • Print
  • Feedback

Resources