[ Team LiB ] Previous Section Next Section

Front-End Programming Using the Struts Framework

To take full advantage of the Struts framework, JSP pages within a WebLogic application have to implement Struts tag libraries that allow them to tie into the back end. Tag libraries, covered in depth in the previous chapters, allow custom HTML tags to be implemented within a JSP page. The Struts tag library creates new tags for virtually every HTML tag. This is done to extend these tags to add Struts-specific properties and to simplify programming JSPs for Web developers who might not have Java skills.

Struts applications usually include at least two tag libraries from Struts:

  • struts-html.tld— Contains all the Struts-specific HTML tags

  • struts-bean.tld— Contains all the Struts-specific JavaBean tags

These files should be included at the beginning of a Struts JSP page just like any other tag libraries the application might need. Here's an example:


<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/lib/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/lib/struts-html.tld" prefix="html" %>

After these are defined, the JSP can be built using the basic Struts tags. Table 19.3 lists some of the more common Struts tags and their HTML equivalent. The entire list is too large to cover in depth. This chapter concentrates on the HTML <form> tag and getting and setting input fields within with the Struts equivalents.

Table 19.3. Common HTML Tags and the Struts Equivalents

HTML Tag

Struts Equivalent

Struts Added Benefit

<html> </html>

<html:html></html:html>

Adds locale support for internationalization

<img>

<html:img>

Adds capability to load from alt text and image from message resources file

<base></base>

<html:base>

Automatically inserts the Web application base

<a> </a>

<html:link></html:link>

Allows the link to be loaded from the request or other bean

NOTE

For a full list of Struts tags and their use, go to http://jakarta.apache.org/struts/userGuide/dev_html.html. That page contains the full documentation and examples that are beyond the scope of this book.


Displaying Text in Struts

Struts handles all displayed text within a configurable message resources file. This allows for internationalization with standard Java internationalization settings for ResourceBundles. The resource path and name are set up in the web.xml file when you register the action servlet. When text must be inserted, a special Struts message tag is available. Refer to the following example:


<bean:message key="login.title"/>

This line inserts the text associated with the key "login.title" into the HTML page. The Struts text insertion method is very simple and straightforward, but highly useful. By default, this tag retrieves the key value from the resource bundle referred to in the <application> parameter tag of the web.xml file. If another bundle is needed, or if another locale than the default is required, the tag has the bundle and locale attributes. The following example gets a fully qualified resource bundle for the French locale:


<bean:message bundle="myapp.props.newConfigFile" locale="FR" key="login.title"/>

Displaying Errors

Struts automatically displays errors if errors are set within the action class or automatic validation with a form bean is active. Within the JSP file, a simple tag is inserted:


<html:errors/>

The actual HTML that will be inserted at runtime is composed of three items:

  • The error header, which is a decoration appearing before the errors. This text is located in a resource bundle under the key mapping errors.header.

  • The list of errors.

  • The footer HTML that's displayed after all the errors; located in errors.footer.

NOTE

Nothing is displayed if the error list is empty.


The following code is a typical entry for the errors.header and errors.footer. Notice the HTML code embedded within.


errors.header=<h5><font color="red">Error Occurred</font>
</h5>Please see the following message(s) before proceeding:<ul>
errors.footer=</ul>

The error tag also has four properties associated with it for configuration purposes:

  • bundle— The name of the resource bundle to locate the errors.header and errors.footer key mappings from.

  • property— The name of the error key to display only certain errors. If this isn't used, all errors are displayed.

  • locale— An optional tag for language-specific messages; defaults to Struts value.

  • name— Name of the request-scope bean where errors have been stored. Defaults to the Action.ERROR_KEY constant.

These properties enable you to define certain conditions and position errors where you need them. To display only the errors for a certain key, just specify a property equal to the error key set when the action error was added. For example:


<html:errors property="result"/>

This is beneficial if you separate errors by field and want to display field error messages for text and data validation.

Using Struts Forms

Forms in Struts were designed to decrease the chance of errors being typed in from the front end. This is accomplished by automatically including input and bean fields within the tags themselves. For instance, using standard HTML, an input field might have a bean associated with a session bean to display information. The code would contain HTML text and some kind of Java call encapsulated in server-side scripting tags. An example of this is displayed here:


<input type="text" name="return" value="<%=sessbean.getValue()%>">

The Struts tag would be much more readable and it would have the bean associated with the input field through the framework, as shown in the following line:


<html:text property="return"/>

This is much easier to code and to read later when it needs to be updated.

A Struts form tag is defined similarly to a <form> tag in HTML:


<html:form action="login.do"
             name="login"
           method="post"
            focus="CUSTOMERNO">
</html:form>

The Struts form tags contain attributes of their HTML equivalents, plus other parameters that make cumbersome tasks easier. The following are some extra useful parameters in the <html:form> tag:

  • focus— The field name within the form to focus on when the user first enters the form. JavaScript is generated and inserted in the page to perform the operation.

  • name— The name of the bean that will be used to populate the input data. This deviates from the HTML use. If the name isn't specified, it is looked up in the action mappings.

  • scope— The scope of the bean that the page uses. If it isn't specified, it's looked up in the action mappings.

  • type— The fully qualified Java class name to the form bean used to populate input. If it isn't specified, it's looked up in the action mappings.

Input fields are specified within the Struts form tag, as with HTML. In Struts, there is no input tag as there is in HTML; rather, the actual widget specified by the input type parameter is used in the Struts tag format. For example, instead of specifying a check box input field that's checked like this:


<input name="coolbox" type="checkbox" <%=(formBean.getCoolbox())?"checked":""%>>

The Struts tag looks like this:


<html:checkbox property="coolbox"/>

Notice the property attribute that contains the name of the input field. The property attribute is linked to the form bean to set the value at display time. In the form bean, a method named getCoolbox() will return a Boolean value: either true (display check) or false (empty check box).

The property value in Struts is contained in all the input tags. This attribute accesses the Struts action form class and gets the associated value from the method. For example,


getCar().getCurrentRadioStation()

would look like this in the property attribute:


property="car.currentRadioStation"

This works the same way in the bean property attribute. This flexibility allows different beans to be reused in applications and hides unnecessary complications.

Listed in Table 19.4 are some of the more common Struts form tags with an example comparing HTML and Struts.

Table 19.4. Common HTML Form Input Elements and Struts Example

Function

HTML Tag

Struts Equivalent

Text field

<input
   type = "text"
   name = "myname"
   size = "20">

<html:text
  property = "myname"
    size = "20" />

Text area

<input
   type = "textarea"
   cols = "50"
   rows = "4"\
   name = "mytarea" >

<html:textarea
  property = "mytarea"
    cols = "50"
    rows = "4">

Radio button

<input
   type = "radio"
   name = "rad1"
   value = "sel1">

<html:radio
  property = "rad1"
    value = "sel1">

Check box

<input
   type = "checkbox"
   name = "chk1"
   value = " sel1">

<html:checkbox
  property = " chk1"
    value = "sel1">

Submit Button

<input
   type = "submit"
   value = "Submit"
   property = "Submit">

<html:submit
Submit>
</html:submit>

Reset button

<input type = "reset">

<html:reset/>

Selection box and options

<select
   name= "item">
<option
   value = "i1">
   Item 1
</option>
</select>

<html:select
  property ="item">
<html:option
   value="i1">
   Item 1
</html:option>
</html:select>

Struts Logic Tags

The Struts application development environment has much more to offer than just simple input and output. The Struts framework also has logic tags for making presentation logic easier. To use these tags within your JSP, add the logic tag library:


<%@ taglib uri="/WEB-INF/lib/struts-logic.tld" prefix="logic" %>

Now it's possible to check conditions on beans and values, match values, and loop without any Java code. The HTML or code to be run is inserted between the beginning and end tags. The following tags are supported:

  • <logic:equal></logic:equal>

  • <logic:notEqual></logic:notEqual>

  • <logic:greaterEqual></logic:greaterEqual>

  • <logic:lessEqual></logic:lessEqual>

  • <logic:greaterThan></logic:greaterThan>

  • <logic:lessThan></logic:lessThan>

Each of the tags compares the value attribute with one of the following:

  • cookie— Compares with the specified cookie

  • header— Compares with a header property

  • parameter— Compares with a request parameter

  • name and property— Compares with a JavaBean specified by the name parameter and the property within the JavaBean

The following example shows how a parameter from a request would be compared with the value tag:


<logic:equal value="Albert Einstein" parameter="Name">
      <b>The Greatest Scientist of all Time!</b>
</logic:equal>

Struts includes the substring matching tags, <logic:match> and <logic:notMatch>. Those tags match on the same attributes as the logic tags, with an additional parameter named location that specifies whether it should match either start or end, as the following example shows:


<logic:notMatch value="Einstein" parameter="Name" location="end">
      <b>Welcome Distinguished Guests</b>
</logic:notMatch>

The final tag we'll examine is the <logic:iterate> tag. This Struts tag is very useful and can very easily display lists of information on dynamic Web pages. The tag is very flexible, and can be used for simple lists or more complex structures. In the following example, we've specified the

  • id— The name of the bean that contains the value for each element of the collection.

  • scope— The place to look for the attribute. page, request, session, application, or anyscope is allowed. If scope isn't present, the default value is page.

  • name— The attribute name that contains the collection to iterate on.

  • type— The type of object that's contained in each row of the collection.

  • length— The maximum number of iterations.

The following code is taken from the sample application for the Struts application named testStruts.war on the companion CD. No other code is needed to use this tag, but it's looking for a session object named order that contains objects of type myApp.Beans.dataBean. If those criteria are in place, the clean look is evident for looping through fields.


<logic:iterate id="mydata"
             name="order"
             type="myApp.Beans.dataBean"
            scope="session" >

  <TR class=bgInner>
    <TD><bean:write name="mydata" property="item"/></TD>
    <TD><bean:write name="mydata" property="qty"/></TD>
    <TD><bean:write name="mydata" property="date"/></TD>
  </TR>
</logic:iterate>

Putting It All Together

Listing 19.3 is a Struts JSP page to process an order search and handle any associated errors. This page displays the last five orders from a session bean provided. The message properties are used to get the titles from the application resource file. The <html:form> tag instantiates and uses a form bean and error messages categorized for each input parameter. Listing 19.3 shows the orderlistdisplay.jsp file to clarify the use and layout of a Struts page.

Listing 19.3 orderlistdisplay.jsp
<%@ page language="java" %>
<%@ include file="style.html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html>
<title><bean:message key="orderentry.title"/></title>
<html:base/>
</head>
<BODY>
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0" WIDTH=100% HEIGHT="136">

<tr><td class=title2 colspan="2">Struts Example Display Items</td></tr>
  <TR>
    <td class=bg height="75" align="right" valign="top" colspan=2>
        &nbsp;
    </td>
 </TR>

<tr>
  <td colspan="2">
  <table class=tableBorder border="0"
   cellspacing="0" cellpadding="0" width="100%">
    <TR class="bgOuter">
        <TD class=title2 align="left" width="33%">

  <table border="0" cellspacing="1" cellpadding="0" width="100%">
  <TR class=bgInner>
        <TD class=title1 width="50%"><bean:message key="prompt.item"/></TD>
        <TD class=title1 width="25%"><bean:message key="prompt.qty"/></TD>
        <TD class=title1 width="25%"><bean:message key="prompt.date"/></TD>
  </TR>
<logic:iterate id="mydata"
             name="order"
             type="myApp.Beans.dataBean"
            scope="session" >

  <TR class=bgInner>
    <TD><bean:write name="mydata" property="item"/></TD>
    <TD><bean:write name="mydata" property="qty"/></TD>
    <TD><bean:write name="mydata" property="date"/></TD>
  </TR>
</logic:iterate>
</table>
<tr>
<td><html:link page="/orderlistentry.jsp">Enter Items</html:link></td>
</tr>
</table>
</td>
</tr>
<tr><td><html:link page="/logout.do">Log Out</html:link></td></tr>
</table>

</body>
</html:html>

Notice how clean the code is in Listing 19.3, without any server-side tags that are usually associated with this type of application. The readability is a definite bonus when Web designers need to modify the page for any reason.

NOTE

The Struts framework includes more features and benefits than can be covered here. For more information about configuring and using the Struts framework, log on to http://jakarta.apache.org/struts/index.html. That site has more examples and specific documentation about Struts. The following are more Struts references:


    [ Team LiB ] Previous Section Next Section