A Walking Tour of the Struts MailReader Demonstration Application
This article is meant to introduce a new user to Struts by "walking through" an application. See the Struts Users Guide and Strut's API for more documentation.
The MailReader application is based on the 1.2.0 build of Struts. To follow along, you should install the MailReader application on your own development workstation (e.g. localhost).
The article assumes the reader has a basic understanding of the Java language, JavaBeans, web applications, and JavaServer Pages. For background on these technologies, see the Preface to the Struts User Guide.
The Struts distribution bundles four applications: struts-documentation, tiles-documentation, struts-example, and struts-examples. This document walks through the struts-example, also known as the "MailReader Demonstration Application".
The premise of the MailReader is that it is the first iteration of a portal application. This version allows users to register themselves and maintain a set of accounts with various mail servers. When completed, the application would let users read mail from their accounts.
The MailReader application demonstrates registering with an application, logging into an application, maintaining a master record, and maintaining child records. This document walks through the JSP pages, Struts Java classes, and Struts configuration elements needed to do these things.
Note that for compatability and ease of deployment, the MailReader uses "application-based" authorization. However, use of the standard Java Authentication and Authorization Service (JAAS) is recommended for most applications. (See the Preface to the Struts User Guide for more about authentification technologies.)
The walkthrough starts with how the initial welcome page is displayed, and then steps through logging in, adding and editing subscriptions, and creating a new registration.
index.jsp
A web application, like any other web site, can specify a list of welcome pages. When you open a web application without specifying a particular page, a welcome page is used by default.
Struts allows developers to manage an application through "virtual pages" called actions. An accepted practice in Struts is to never link directly to server pages, but only to these actions. The actions are listed in a configuration file. By linking to actions, developers can "rewire" an application without editing the server pages.
"Link actions not pages."
Unfortunately, actions cannot be specified as a welcome page. Since there can be a list of pages, the web server looks for each page on the list before selecting one. The web server doesn't see actions as pages and will never select one as a welcome page. So, in the case of a welcome page, how do we follow the Struts best practice of navigating through actions rather than pages?
One solution is to use a server page to "bootstrap" a Struts action. A Java web application recognizes the idea of "forwarding" from one page to another page (or action). We can register the usual "index.jsp" as the welcome page and have it forward to a "Welcome" action. Here's the MailReader's index.jsp:
<%@ taglib uri="/tags/struts-logic" prefix="logic" %> <logic:redirect action="/Welcome"/>
At the top of the page, we import the "struts-logic" JSP tag library. (Again, see the Preface to the Struts User Guide for more about the technologies underlying Struts.) The page itself consists of a single tag that redirects to the "Welcome" action. The tag inserts the actual web address for the redirect when the page is rendered. But, where does the tag find the actual address to insert?
The list of actions, along with other Struts components, are registered through one or more Struts configuration files. The configuration files are written as XML documents and processed when the application starts. If we just wanted to forward to the welcome page, we could use a configuration element like this:
<!-- Display welcome page --> <action path="/Welcome" forward="/welcome.jsp" />
If someone asked for the Welcome action ("/Welcome.do"), the welcome.jsp page would be displayed in return.
WelcomeAction.java
But if we peek at the configuration file for the MailReader, we find a slightly more complicated XML element for the Welcome action:
<!-- Display welcome page --> <action path="/Welcome" type="org.apache.struts.webapp.example.WelcomeAction"> <forward name="failure" path="/Error.jsp" /> <forward name="success" path="/welcome.jsp" /> </action>
Here, the "WelcomeAction" Java class executes whenever someone asks for the Welcome action. As it completes, the Action class can select which page is displayed. Two pages the class can select here are "Error.jsp" and "welcome.jsp". But the Action class doesn't need to know the path to the pages. The class can select them just using the names "success" or "failure".
OK ... but why would a WelcomeAction want to choose between success and failure?
The MailReader application retains a list of users along with their email accounts. The application stores this information in a database. If the application can't connect to the database, the application can't do its job. So before displaying the welcome page, the class checks to see if the database is available. The MailReader is also an internationalized application. So, the WelcomeAction checks to see if the message resources are available too. If both resources are available, the class forwards to the "success" path. Otherwise, it forwards to the "failure" path so that the appropriate error messages can be displayed.
MemoryDatabasePlugIn.java
The database is exposed to the application as an object stored in application scope. The database object is based on an interface. Different implementations of the database could be loaded without changing the rest of the application. But how is the database object loaded in the first place?
One section of the Struts configuration is devoted to "PlugIns". When a Struts application loads, it also loads whatever PlugIns are specified in its configuration. The PlugIn interface is quite simple, and you can use PlugIns to do anything that might need to be done when your application loads. The PlugIn is also notified when the application shuts down, so you can release any allocated resources.
<plug-in className="org.apache.struts.webapp.example.memory.MemoryDatabasePlugIn"> <set-property property="pathname" value="/WEB-INF/database.xml"/> </plug-in>
By default, the MailReader application loads a "MemoryDatabase" implementation of the UserDatabase. MemoryDatabase stores the database contents as a XML document, which is parsed by the Digester and loaded as a set of nested hashtables. The outer table is the list of user objects, each of which has its own inner hashtable of subscriptions. When you register, a user object is stored in this hashtable ... and when you login, the user object is stored within the session context.
The database comes seeded with a sample user. If you check the database.xml file under WEB-INF, you'll see the sample user described as:
<user username="user" fromAddress="John.User@somewhere.com" fullName="John Q. User" password="pass"> <subscription host="mail.hotmail.com" autoConnect="false" password="bar" type="pop3" username="user1234"> </subscription> <subscription host="mail.yahoo.com" autoConnect="false" password="foo" type="imap" username="jquser"> </subscription> </user>
This creates a registration record for "John Q. User", with the detail for his hotmail account (or "subscription").
MessageResources.properties
Another section of the Struts configuration loads the message resources for the application. If you change a message in the resource, and then reload the application, the change will appear throughout the application. If you provide message resources for additional locales, you can internationalize your application.
<message-resources parameter="org.apache.struts.webapp.example.MessageResources" />
This is a standard properties text file. Here are the entries used by the welcome page:
index.heading=MailReader Demonstration Application Options index.logon=Log on to the MailReader Demonstration Application index.registration=Register with the MailReader Demonstration Application index.title=MailReader Demonstration Application (Struts 1.2.1-dev) index.tour=A Walking Tour of the MailReader Demonstration Application
The MailReader application uses a second set of message resources for non-text elements. The "key" element can be used to access this resource bundle rather than the default bundle.
<message-resources parameter="org.apache.struts.webapp.example.AlternateMessageResources" key="alternate" />
welcome.jsp
After confirming that the necessary resources exist, the WelcomeAction forwards to the welcome.jsp page.
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <html> <head> <title><bean:message key="index.title"/></title> <link rel="stylesheet" type="text/css" href="base.css" /> </head> <h3><bean:message key="index.heading"/></h3> <ul> <li><html:link action="/EditRegistration?action=Create">
<bean:message key="index.registration"/></html:link></li> <li><html:link action="/Logon"><bean:message key="index.logon"/></html:link></li> </ul> <h3>Change Language</h3> <ul> <li><html:link action="/Locale?language=en">English</html:link></li> <li><html:link action="/Locale?language=ja" useLocalEncoding="true">Japanese</html:link></li> <li><html:link action="/Locale?language=ru" useLocalEncoding="true">Russian</html:link></li> </ul> <hr /> <p><html:img bundle="alternate" pageKey="struts.logo.path" altKey="struts.logo.alt"/></p> <p><html:link action="/Tour"><bean:message key="index.tour"/></html:link></p> </body> </html>
At the top of the welcome.jsp page, there are several directives that load the Struts tag libraries. These are just the usual red tape that goes with any JSP file. The rest of the page demonstrates three Struts JSP tags: "bean:message", "html:link", and "html:img".
The bean:message tag inserts a message from the MessageResources file. The MailReader comes with support for three locales: English (the default), Russian, and Japanese. If the Struts locale setting is changed for a user, the bean:message tag will render messages from that locale's property bundle instead.
The html:link tag does double duty. First, you can refer to an action or forward stored in the Struts configuration, and the tag will insert the corresponding path when the page is rendered. This makes it easy to "rewire" an application without touching all the pages. Second, the link tag will "URL encode" the hyperlink to maintain the client session. Your application can maintain client state without requiring cookies.
If you turn cookies off in your browser, and then reload your browser and this page, you will see the links with the Java session id information attached. (If you are using Internet Explorer and try this, be sure you reset cookies for the appropriate security zone, and that you disallow "per-session" cookies.)
The html:img tag renders an img tag. When necessary, the src URI is encoded as it is with the link tag. In this case, the tag inserts the src path from the "alternate" MessageResource bundle, along with the text for the alt element.
In the span of a single request, Struts has done quite a bit already:
- Confirmed that required objects were created during initialization.
- Written all the page headings and labels from internationalized message resources.
- Automatically URL-encoded paths as needed.
When rendered, the welcome page lists two menu options: one to register with the application and one to login in (if you have already registered). Let's follow the login link first.
logon.jsp
If you choose the logon link, the Logon action forwards control to the logon.jsp page. The logon page displays a form that accepts a username and password. You can use the default username and password to logon (user and pass). Note that both the username and password are case sensitive. Better yet, try omitting or misspelling the username and password in various combinations and see how the application reacts.
Here's how the login.jsp is coded:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <html:xhtml/> <html> <head> <title><bean:message key="logon.title"/></title> </head> <html:errors/> <html:form action="/SubmitLogon" focus="username" onsubmit="return validateLogonForm(this);"> <table border="0" width="100%"> <tr> <th align="right"> <bean:message key="prompt.username"/>: </th> <td align="left"> <html:text property="username" size="16" maxlength="18"/> </td> </tr> <tr> <th align="right"> <bean:message key="prompt.password" bundle="alternate"/>: </th> <td align="left"> <html:password property="password" size="16" maxlength="18" redisplay="false"/> </td> </tr> <tr> <td align="right"> <html:submit property="Submit" value="Submit"/> </td> <td align="left"> <html:reset/> </td> </tr> </table> </html:form> <html:javascript formName="LogonForm" dynamicJavascript="true" staticJavascript="false"/> <script language="Javascript1.1" src="staticJavascript.jsp"></script> <jsp:include page="footer.jsp" /> </body> </html>
We saw some of these tags on the welcome page. Let's focus on the new tags.
The first new tag on the logon page is "html:errors". The credentials you entered are processed by a "LogonAction" class. If the credentials are incorrect, the LogonAction posts an appropriate error message and forwards back to the input page. If the html:errors tag sees that one or more messages were posted, the tag ouputs the messages to the page. The text of the messages can be specified in the MessageResource bundle, making them easy to internationalize.
The second new tag is "html:form". This tag renders a html form tag. The "action" element tells the tag to use "SubmitLogon.do" for the form's action. The "focus" attribute tells the tag to generate a little Javascript after the form that sets its focus to the "username" field. The "onsubmit" attribute tells the form to run a Javascript when the form is submitted. (Just like the corresponding attribute on the standard form tag.)
Within the html:form tag, we see four other new tags: "html:text", "html:password", "html:submit", and "html:reset".
The html:text tag renders a "input type=text" tag. The "property" attribute becomes the input tag's "name" attribute.
The html:password tag renders a "input type=password" tag. The "redisplay" attribute tell the tag not to render the password back into the file, if the submit fails. The html:submit and html:reset tags render buttons of the corresponding types.
Following the form is a "html:javascript" tag. This tag works with the Struts Validator component to generate a JavaScript that can validate input before it is submitted to the LogonAction.
Most of these tags have many more options than the ones we use in this application. For the complete documentation for each tag, see the Tag Developers Guides in the Struts documentation bundle.
But, how do these tags know so much? How does the Javascript tag know what scripts to write? How do the text and password tags know what values to redisplay?
For the answers, we need to turn to the Struts configuration files, "struts-config.xml" and "validation.xml".
struts-config.xml
In the struts-config.xml file, we find an element for the "/SubmitLogon" action
<!-- Process a user logon --> <action path="/SubmitLogon" type="org.apache.struts.webapp.example.LogonAction" name="LogonForm" scope="request" input="logon"> <exception key="expired.password" type="org.apache.struts.webapp.example.ExpiredPasswordException" path="/ExpiredPassword.do"/> </action>
We saw the path and type attributes in the Welcome action. Let's look at the new attributes.
The "name" attribute specifies something Struts calls an "ActionForm". The ActionForm buffers input from a form and delivers it to an Action class as an object. The ActionForm can also validate the input. If validation fails, the tags can rewrite the input values from the ActionForm.
The ActionForms are defined in the "formbeans" section of the configuration file. Here's the formbean element for the "LogonForm".
<form-bean name="LogonForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="username" type="java.lang.String"/> <form-property name="password" type="java.lang.String"/> </form-bean>
ActionForms can be "conventional" or "dynamic". Here, we are using a dynamic ActionForm. Rather than cobble up an actual JavaBean class, we specify the properties the ActionForm can accept in the configuration file. If the property is not specified here, it is not captured, validated, or passed up to the Action class.
Struts creates the ActionForms automatically. The "scope" attribute in the action element tells the controller wether to store the ActionForm in the request or in the user's session.
The Struts best practice is to use request scope for single-page forms that contain all the properties needed by the Action. There is usually no need to maintain form data across requests.
Struts can also validate the ActionForm automatically. If validation fails, Struts looks for the forward specified by the "input" attribute. In this case, the "logon" forward sends control back to the input.jsp page.
<forward name="logon" path="/Logon.do"/>
Within the logon action element is another new element, "exception". When a user logons on, it's possible that an "ExpiredPasswordException" will be thrown. Should this happen, Struts will capture the exception and send control to the "ExpiredPassword" action.
validations.xml
In the logon.jsp, we mentioned that the html:javascript tag confers with the Struts Validator components. The Validator is configured through another XML document, the "validation.xml". Here's the element for our LogonForm:
<form name="LogonForm"> <field property="username" depends="required"> <arg0 key="prompt.username"/> </field> <field property="password" depends="required, minlength,maxlength"> <arg0 key="prompt.password"/> <arg1 key="${var:minlength}" name="minlength" resource="false"/> <arg2 key="${var:maxlength}" name="maxlength" resource="false"/> <var> <var-name>maxlength</var-name> <var-value>16</var-value> </var> <var> <var-name>minlength</var-name> <var-value>3</var-value> </var> </field> </form>
The field elements correspond to the ActionForm properties. The "username" field element says it depends on the "required" validator. If the username is blank or absent, validation will fail and an error message is automatically generated.
The "password" field (or property) is also required. In addition, it must also pass the "maxlength" and "minlength" validations. Here, the minimum length is three characters and the maximum length is sixteen. If the length of the password doesn't meet these criteria, a corresponding error message is generated. Of course, the messages are generated from the MessageResource bundles and are easy to localize.
LogonAction.java
If validation passes, the LogonForm object is forwarded to the LogonAction. The LogonAction interacts with the database to see if the credentials are valid. If so, the user is logged on, and control passes to the "success" forward. Otherwise, control is forwarded to the input page and the list of error messages displayed.
Here's the LogonAction (sans comments):
package org.apache.struts.webapp.example; import ... public final class LogonAction extends BaseAction { private static String USERNAME = "username"; private static String PASSWORD = "password"; User getUser(UserDatabase database, String username, String password, ActionMessages errors) throws ExpiredPasswordException { User user = null; if (database == null){ errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.database.missing")); } else { user = database.findUser(username); if ((user != null) && !user.getPassword().equals(password)) { user = null; } if (user == null) { errors.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.password.mismatch")); } } return user; } void SaveUser(HttpServletRequest request, User user) { HttpSession session = request.getSession(); session.setAttribute(Constants.USER_KEY, user); if (log.isDebugEnabled()) { log.debug( "LogonAction: User '" + user.getUsername() + "' logged on in session " + session.getId()); } } public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UserDatabase database = getUserDatabase(request); String username = (String) PropertyUtils.getSimpleProperty(form, USERNAME); String password = (String) PropertyUtils.getSimpleProperty(form, PASSWORD); ActionMessages errors = new ActionMessages(); User user = getUser(database,username,password,errors); SaveUser(request,user); if (!errors.isEmpty()) { this.saveErrors(request, errors); return (mapping.getInputForward()); } return (findSuccess(mapping)); }
MainMenu.do and mainMenu.jsp
On a successful logon, the Main Menu page displays. If you logged in using the default account, the page title should be "Main Menu Options for John Q. User". Below this legend should be two links:
- Edit your user registration profile
- Log off MailReader Demonstration Application
If you check the address shown by your browser, you will see that it shows "/SubmitLogon.do" not "/MainMenu.do". The Java servlet platform supports the idea of server-side forwards. When control passed from the SubmitLogon action to the MainMenu action, everything occured server-side. All the browser knows is that we are looking at the result of submitting a form to "/LogonSubmit.do", so that's the address that shows. It doesn't know control passed from one action to another. The difference between server-side forwards and client-side redirects is subtle and often confuses new developers.
If you change the address to "/MainMenu.do" and press enter, the same page will display again.
Here's the JSP source for the "MainMenu" action and the "mainMenu.jsp".
<action path="/MainMenu" forward="/mainMenu.jsp"/>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="/tags/app" prefix="app" %> <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <app:checkLogon/> <html> <head> <title><bean:message key="mainMenu.title"/></title> <link rel="stylesheet" type="text/css" href="base.css" /> </head> <h3><bean:message key="mainMenu.heading"/> <bean:write name="user" property="fullName" /></h3> <ul> <li><html:link action="/EditRegistration?action=Edit"><bean:message key="mainMenu.registration"/></html:link></li> <li><html:link forward="logoff"><bean:message key="mainMenu.logoff"/></html:link></li> </ul> </body> </html>
If you check the source for mainMenu.jsp, you will find two new tags: "app:checkLogon" and "bean:write". Let's look at the bean tag first.
When control passed through the LogonAction, it retrieved a "User" object from the database and stored a reference in "session" scope. This object is a JavaBean with several properties. One property is "fullName". The bean:write tag can find the User bean and print the fullName property for us.
But how can the page be sure that we are logged in and that the User object exists?
At the top of the page, above the "html" tag, is the other new tag, checkLogon. This tag, true to its name, checks to see of the user is logged on. If not, the tag forwards to the LogonAction. Let's have a look:
package org.apache.struts.webapp.example; import ... public final class CheckLogonTag extends TagSupport { private String name = Constants.USER_KEY; private static String LOGIN_PATH = "/Logon.do"; private String page = LOGIN_PATH; public int doStartTag() throws JspException { return (SKIP_BODY); } public int doEndTag() throws JspException { boolean valid = false; HttpSession session = pageContext.getSession(); if ((session != null) && (session.getAttribute(name) != null)) { valid = true; } if (valid) { return (EVAL_PAGE); } else { ModuleConfig config = (ModuleConfig) pageContext.getServletContext().getAttribute( org.apache.struts.Globals.MODULE_KEY); try { pageContext.forward(config.getPrefix() + page); } catch (ServletException e) { throw new JspException(e.toString()); } catch (IOException e) { throw new JspException(e.toString()); } return (SKIP_PAGE); } } public void release() { super.release(); this.name = Constants.USER_KEY; this.page = LOGIN_PATH; } }
As tags go, CheckLogon is quite simple. It takes no attributes. It's just hardwired to check for a User object in session scope and forward to the LogonAction if the object is missing.
Simple but effective. Try following the logout link and then putting in the "/MainMenu.do" address by hand. If you do, the tag will automatically forward you to the logon page. For any page that requires a login, we simply need to add a checkLogon tag at the top (before any of the page is written).
Many Struts developers would frown on the CheckLogon tag solution. They might argue that a page should not need to know about logons. We shouldn't rely on people remembering to put a CheckLogon tag on every protected page. And "they" would be right! We do recommend that most applications use standard JAAS. Perhaps in the next iteration, the MailReader developers will do just that. But for now, the CheckLogon tag is a simple solution to a simple problem.
The other links we've seen have either gone directly to a JSP file, or to a Struts action path, like Login.do. The "Edit your user registration profile" link is a little different, since it also uses a parameter, as in EditRegistration.do?action=Edit. When the Struts ActionServlet processes this link, it will ignore the parameter for the purpose of matching the request, but still pass the parameter along to action's object.
This means that in Struts, an action object must be able to handle every valid parameter for it's base path. (In the Example, EditRegistration must handle both Edit and Create.)
You may want to check for invalid parameters too. (And be careful of differences in case if your comparisons are not case insensitive!)
If you check the struts-config.xml, you'll see that the EditRegistration action is mapped to the (surprise again!), the EditRegistrationAction; it uses a RegistrationForm bean, and registration.jsp for input.
<!-- Registration form bean -->
<form-bean name="RegistrationForm"
type="org.apache.struts.webapp.example.RegistrationForm"/>
<!-- Edit user registration -->
<action path="/EditRegistration"
type="org.apache.struts.webapp.example.EditRegistrationAction"
name="RegistrationForm"
scope="request"
validate="false"
input="/registration.jsp">
<forward name="success" path="/registration.jsp"/>
</action>Hint: Consistent naming conventions, like the ones used throughout the Example, make applications much easier to write and understand. Save your creativity for the things that matter, and follow an established standard for source code formatting, like the Elements of Java Style.
EditRegistrationAction.java
Many objects in an application may do double-duty. For example, EditRegistrationAction not only lets you update a registration, but is also used to create a new one. Which task the object performs is determined by the action passed to it. In the case of EditRegistrationAction, it can either edit or create a registration, the default being create if a task is not specified. To select between tasks, simply add ?create or ?edit to the hyperlink or form action.
Like most classes in the example application, editRegistration makes good use of the log to track it's progress. Note that ActionServlet has had a new log method added since the Example was written. You can now specify both the message and a minimum logging (or debug) level. For more, see the Javadoc in your struts-documentation application.
registration.jsp and RegistrationForm.java
If you follow the "Edit your user registration profile" link from the mainMenu, we will finally reach the heart of the Example application, the registration page. This page displays everything the Example application knows about you (or at least your login), while demonstrating several interesting techniques.
You'll remember that mainMenu.jsp wanted to be sure that everyone was logged in, and used the CheckLogin tag to enforce that. The registration.jsp is a little different. First it uses a Struts logic tag to see if the task at hand is to register a new User. If not (e.g. action != "Create"), the logic tag exposes a CheckLoginTag to be sure we have a user (and therefore a registration) to edit.
<logic:equal
name="RegistrationForm"
property="action"
scope="request"
value="Edit"
>
<app:checkLogon/>
</logic:equal>Note that the Struts html:form tag will refer to properties set by struts-config.xml and automatically create a RegistrationForm bean if one is not present. However, that does not happen until the form tag is processed within the page. Since this block appears before the html:form tag, a runtime error is exposed if you try to access registration.jsp directly (rather then going through the EditRegistration.do action).
registation.jsp continues to use logic tags throughout the page so that a single JSP can be used to perform more than one task. For example, if you are editing the form (action == "Edit"), the page inserts your username from the RegistrationForm bean. If you are new user (action == "Create"), the page creates an empty field, so you can pick your username.
The Struts logic tags are a very convenient way to express application logic within your pages. This prevents user error and reduces the number of JSPs your application needs to maintain, among other benefits.
The page also uses logic tags to display a list of subscriptions for the given user. If the user enters this page with an edit action in the request context, the lower part of the page listing the subscriptions is exposed by this logic tag:
<logic:equal
name="RegistrationForm"
property="action"
scope="request"
value="Edit"
>Otherwise, the page just contains the top portion -- a blank data-entry form for creating the user's registration.
logic:iterate
Beside making the usual conditional tests, you can also use logic tags to forward control to other actions, to redirect control to another path, and to iterate over collections. The registration page includes a good example of using the logic:iterate tag to display the user's subscriptions.
The subscriptions are stored in a hashtable object, which is in turn stored in the user object. So to display each subscription, we have to reach into the user object, and loop through the members of the subscription collection. Using the iterate tag, this couldn't be easier.
<logic:iterate name="user" property="subscriptions" id="subscription">
<!-- block to repeat -->
</logic:iterate>The three parameters to the iterate tag ( name, property, and id) tell it to
- Check this context for an attribute (e.g. object) named "user",
- Snag the property of user named "subscriptions",
- In the block to iterate, use "subscription" (singular) as the name for each member of the collection.
So, to list the host for each subscription in a HTML unordered list, we could write:
<ul>
<logic:iterate name="user" property="subscriptions" id="subscription">
<li>
<bean:write name="subscription" property="host" filter="true" />
</li>
</logic:iterate>
</ul>This is another good example of how Struts works with the standard JSP tags, like bean. The filter option says to use convert HTML commands to their character entity. So a < would be output in the HTML as <.
In registration.jsp, iterate is used to create a menu of subscriptions, each linked with an edit and delete action.
<logic:iterate id="subscription" name="user" property="subscriptions">
<tr>
<td align="left">
<bean:write name="subscription" property="host" filter="true"/>
</td>
<td align="left">
<bean:write name="subscription" property="username" filter="true"/>
</td>
<td align="center">
<bean:write name="subscription" property="type" filter="true"/>
</td>
<td align="center">
<bean:write name="subscription" property="autoConnect"/>
</td>
<td align="center">
<app:linkSubscription page="/EditSubscription.do?action=Delete">
<bean:message key="registration.deleteSubscription"/>
</app:linkSubscription>
<app:linkSubscription page="/EditSubscription.do?action=Edit">
<bean:message key="registration.EditSubscription"/>
</app:linkSubscription>
</td>
</tr>
</logic:iterate>The collection in an iterate tag can be any of the following: an array of objects, an Iterator, a Collection (which includes Lists, Sets and Vectors), or a Map (which includes Hashtables) whose elements will be iterated over.
You'll note that the hyperlinks to the edit and delete action for each subscription are written with another custom tag, app:linkSubscription. Writing a hyperlink to an action is not difficult, but it can be ugly, and makes an excellent case for encapsulation. If you trace through the app.tld, you will find that the source code for the linkSubscription tag lives in (come on, take a guess) LinkSubscriptionTag.java.
LinkSubscriptionTag.java
The Example application uses a subscription's host name (e.g. yahoo.com) as a primary key, which means you can only have one subscription for each host. It also means that to edit a subscription, all you need to know is the user and host. In fact, the EditSubscription action is designed to create, edit, or delete a subscription if provided a user and host names in the request. The goal of LinkSubscriptionTag is then to output a block like:
<A HREF=[path]EditSubscription.do?action=[action]&username=[user]&host=[host]">[action]
</A>based on input block like:
<app:linkSubscription
page="/EditSubscription.do?action=Delete">Delete
</app:linkSubscription>To reduce overhead, LinkSubscriptionTag uses "subscription" as the default name (which the iterator refers to as "ID"), so that can be omitted from the tag properties. The "action" portion of the will differ, and so that is given as the page property to the tag
Here are a few annotated highlights from LinkSubscriptionTag.java:
- Create a string buffer, and ask the request for the relative path to the application
StringBuffer url = new StringBuffer(request.getContextPath());
- Snag a reference to the subscription bean (for this iteration)
subscription = (Subscription) pageContext.findAttribute(name);
- Append the username and host from the bean to the path request.
url.append("&username="); url.append(BeanUtils.filter(subscription.getUser().getUsername()));
url.append("&host=");
url.append(BeanUtils.filter(subscription.getHost()));These are the essentials, but be sure to see the full source in LinkSubscriptionTag.java for the rest of the error and logic checking that a working application needs to succeed.
Meanwhile, back on registration.jsp, there is one more link on the page. This uses yet another custom tag, the app:linkUser tag.
<app:linkUser page="/EditSubscription.do?action=Create">
<bean:message key="registration.addSubscription"/>
</app:linkUser>By this time, you must be ready to flip directly to LinkUserTag.java with nary a glance at the configuration file ...
LinkUserTag.java
Since they solve the same general problem, LinkUserTag and LinkSubscriptionTag are quite a bit a like, except that LinkUserTag grabs the user bean from the session context, instead of a subscription bean from the iteration. Like the LinkSubscriptionTag, the name for the user bean (e.g. "user") is defaulted, and can be omitted from the tag; all that's needed is the page property -- the rest is automatic!
<app:linkUser page="/EditSubscription.do?action=Create">
<bean:message key="registration.addSubscription"/>
</app:linkUser>When rendered, this displays a HTML hypertext link like:
<a href="/struts-example/EditSubscription.do?action=Create&username=user">
Add
</a>Note that anchor links with ampersands should use the character entity & as the LinkUserTag has done here (http://www.w3.org/TR/html401/appendix/notes.html#h-B.2.2).
Let's follow that "Add" link now and see what's up with the EditSubcription action anyway.
EditSubscriptionAction.java
Predictably, we find a some now-familiar mappings in struts-config.xml
<!-- Subscription form bean -->
<form-bean
name="SubscriptionForm"
type="org.apache.struts.webapp.example.SubscriptionForm"
/>
<!-- Edit mail subscription -->
<action path="/EditSubscription"
type="org.apache.struts.webapp.example.EditSubscriptionAction"
name="SubscriptionForm"
scope="request"
validate="false"
>
<forward name="failure" path="/mainMenu.jsp"/>
<forward name="success" path="/subscription.jsp"/>
</action>When we've introduced these type of mappings before, and mentioned that the struts-config.xml was parsed when the ActionServlet was initialized. But we should make it clear that when the Struts digester parsed this file, it actually created standard Java objects, linked as properties to the controller. This means you don't have to edit Java source files just to add a bunch of "new" statements. (How cool is that?)
Following what was specified by struts-config.xml, the controller makes sure that a SubscriptionForm bean exists, along with the SubscriptionAction object, and then calls the action object's perform method. The perform method first checks to see that the user is logged-in. If not, control is forwarded to the Login action. EditSubscriptionAction.perform then either creates a new subscription object (if the task is Create), or searches the user's subscription hashtable for a matching hostname (if the task is Edit).
Finally, EditSubscriptionAction conforms the ActionForm bean with the database bean. There may be several subscriptions in the database, but in EditSubscriptionAction we expose the one selected (or just created) for this request to use. Once the Action form (called "subform" in the code) is created and populated from the database, the bean's action is set to either Create or Edit, and control is forwarded to our "success" form, subscription.jsp .
Note that the servlet only creates one object for each action. Each request is handled as a separate thread, and passed to the single action object instance. This means your action objects must be multi-thread safe.
But before turning to our final JSP, a word about our database model ...
User.java and Subscription.java
If you're used to working with relational databases, the links between the user and subscription objects may be confusing. A conventional relational database would create two distinct tables, one for the users and another for the subscriptions, and link them together with a user ID. The Example application implements a different model, a hierarchical database. Here a "table" of subscriptions is stored within each user object, something like the way a filing system stores documents within folders.
In addition to the usual getters and setters, the user object also has two methods for working with subscription objects. findSubscription takes a hostname and returns the subscription object for that host. getSubscriptions returns an array of all the subscriptions for the user (ready-made for the iterate tag!). Besides the fields needed to manage the SubscriptionForm data, the object also maintains a runtime link to its user object.
To create a new subscription, EditSubscriptionAction.java simply creates a new subscription object, and sets its user to the object found in the request, and then forwards control to its input form, subscription.jsp.
subscription.jsp
Saving the best for last, subscription.jsp demonstrates use of some interesting Struts custom form tags, html:options and html:checkbox.In registration.jsp, the Struts iteration tag was used to write a list of subscriptions. Another place where iterations and collections are handy is the option list for a HTML select tag. Since this is such a common situation, Struts offers a html:options (plural) tag can take an array of objects as a parameter. The tag then iterates over the members of the array (beans) to place each one inside an standard option tag. So given a block like
<html:select property="type">
<html:options
collection="serverTypes"
property="value"
labelProperty="label"
/>
</html:select>Struts outputs a block like
<select name="type">
<option value="imap" selected>IMAP Protocol</option>
<option value="pop3">POP3 Protocol</option>
</select>Here, one collection contained both the labels and the values, from properties of the same name. Options can also use a second array for the labels, if they do not match the values. Options can use a Collection, Iterator, or Map for the source of the list.
For demonstrations purposes, the serverTypes array is created at the top of this page. Usually, the html:options tag would be used to list valid items from a database maintained elsewhere. For example, if the application needed you to select a default subscription, a form might list the subscriptions in an options tag.
The LabelValueBean used to create the demonstration array is also a good example of simple but useful bean object.
A particularly tricky HTML control is the checkbox. A problem with a checkbox is that it is only sent in the request if it is checked. If it is not checked, it is not sent (i.e. null). This can be problematic when trying to validate the form's data after it has been translated to a bean. The autoconnect property for a subscription demonstrates how to handle validation of a checkbox.
SubscriptionForm.java
Struts validation is handled by the reset and validate methods of the ActionForm bean. When creating your own form beans, you should subclass ActionForm, add your own fields and their getters/setters, and implement the reset and validate methods.
Struts calls reset before populating the form, and calls validate after populating it but before the perform method of the action. Reset should assign default values to each of your form fields, usually null. But in the case of checkboxes, the default value should usually be false instead of null.
For more examples of validating forms, take another look at LoginForm.java and RegistrationForm.java.
Back in subscription.jsp, we have one more block to cover. Although the same basic form can be used to created, edit, or delete a subscription, people might expect the buttons to be labeled differently in each case. subscription.jsp accommodates by using a logic tag to output a different set of buttons for each case. This doesn't really change the way subscription.jsp works, but it does make things less confusing for the user.
<logic:equal
name="SubscriptionForm"
property="action"
scope="request"
value="Create">
<html:submit>
<bean:message key="button.save"/>
</html:submit>
</logic:equal>In the case of a request to delete a subscription, the submit button is labeled "Confirm", since this view is meant to give the user a last chance to cancel, before sending that task along to SaveSubscriptionAction.java.
The actual action property is placed into the form as a hidden field, and SaveSubscriptionAction checks that property to execute the appropriate task.
SaveSubscriptionAction.java
Our final stop has the job of finishing what EditSubscriptionAction.java and subscription.jsp started. After the usual logic and error checking, SaveSubscriptionAction either deletes or updates the subscription object being handled by this request, and cleans up the bean, just to be tidy. By now, you should be very comfortable reading through the source on your own, to pickup the finer points.
This concludes our tour. To review, you may wish to trace the path a new user takes when they register with the application for the first time. You should also read over each of the .java and JSP files carefully, since we only covered the high points here.
Summary
- Struts uses a single controller servlet to route HTTP requests.
- The requests are routed to action objects according to path (or URI).
- Each request is handled as a separate thread
- There is only one object for each action (URI), so your action objects must be multi-thread safe.
- The configuration of action objects are loaded from a XML resource file, rather than hardcoded.
- Action objects can respond to the request, or ask the controller to forward the request to another object or to another page, such as an input form.
- A library of custom tags works with the rest of the framework to enhance use of JavaServer Pages.
- The Struts form tag can work closely with an action objects via a Struts ActionFormBean to retain the state of a data-entry form, and validate the data entered.
- ActionForm beans can be automatically created by the JSP form or controller servlet.
- Struts supports a message resource for loading constants strings. Alternate message resources can be provided to internationalize an application.