The validate method in a Struts form bean acts as a kind of firewall between the input pages and the Struts actions, only letting validated data into the actions.. ? Add an import statem
Trang 1Because we use this form bean on multiple input pages, we have to know which of the fields should be validated We use the validateKey string for this purpose On the JSPs where this form bean is used, we pass an appropriate value for the validateKey so we can validate the data entered on that particular page only
The validate method in a Struts form bean acts as a kind of firewall between the input pages and the Struts actions, only letting validated data into the actions The validate method is useful for performing simple validation such
as verifying that data has actually been submitted, has the correct length, and
so forth However, it is not the appropriate place to do more advanced validation, such as calling an EJB to validate that a customer number really exists That type of validation is best carried out by the actions themselves The validate method returns an org.apache.struts.action.ActionErrors object with the keys for the errors it has found This is used by the JSPs to inform the user that an entry has to be corrected
When done, save and close the CustomerInfoForm class
Implement the transactionForm form bean using the same method This class should be called TransactionForm and have the following fields:
destinationAccount String (for transfer only)
transactions itso.bank.model.TransRecord[]
(retrieved for an account) Make sure the form is added to struts-config.xml with the mapping name transactionForm
Add an import statement:
import itso.bank.util.AmountConverter;
Replace the definition of the action field at the beginning of this class with the following line:
private String action = "ListTransactions";
This will make Struts select the List Transactions option in the accountDetails.jsp page so that it will be the default
Set the default value also in the reset method:
action ="ListTransactions";
Replace the validate method with the code shown in Figure 10-18 The code
is available in:
Trang 2Figure 10-18 TransactionForm validate method
This method uses the action string to determine what fields should be validated
Press Ctrl-S to save this class and then close the Java editor
public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (action != null && action.trim().length() != 0) {
if ("Deposit".equals(action)
|| "Withdraw".equals(action)
|| "Transfer".equals(action)) {
if (amount == null || amount.trim().length() == 0)
errors.add(
ActionErrors.GLOBAL_ERROR, new ActionError("error.missing.amount"));
else
try {
java.math.BigDecimal a = AmountConverter.fromString(amount);
if (a.compareTo( new java.math.BigDecimal(0.00) ) <= 0) errors.add(
ActionErrors.GLOBAL_ERROR, new ActionError("error.invalid.amount"));
} catch (Exception e) {
errors.add(
ActionErrors.GLOBAL_ERROR, new ActionError("error.invalid.amount"));
}
}
if ("Transfer".equals(action)) {
if (destinationAccount == null
|| destinationAccount.trim().length() == 0)
errors.add(
ActionErrors.GLOBAL_ERROR, new ActionError("error.missing.destinationAccount"));
}
}
return errors;
}
Trang 3When the form beans are implemented, they show up colored in the Web diagram The next step is to implement the Web pages
Developing the JSPs
We start by implementing the index.jsp page:
Double-click the index.jsp page This opens up the New JSP File dialog as shown in Figure 10-19 The defaults are fine, so click Next
Figure 10-19 New JSP File wizard
Note: If deleting a component from the Web diagram, you are prompted
whether you also want to delete the underlying resource Underlying resource here refers to the mapping in the struts-config.xml file, not the implemented component itself This means that if you delete a form bean and also delete the underlying resource, it will remove the form bean from the Web diagram and its mapping from the struts-config.xml file It will not, however, delete the Java source or class file for the form bean If you then add a new form bean with the same name to the Web diagram and attempt to implement it, the Finish button that you must click to create the component is deactivated in the wizard This is due to the fact that this class already exists, it was not deleted
Trang 4 On the tag libraries page (Figure 10-20), you can add the tag libraries that the JSP requires The wizard has already added the two most commonly used Struts tag libraries, html and bean Our index.jsp page does not require any other tag libraries, so click Next
Figure 10-20 Add tag libraries
On the tag directive page, select Create Session Variable and true
(Figure 10-21) Click Next
Figure 10-21 JSP page directive
Trang 5 On the next two dialogs in the wizard, you can click Next and use the defaults These dialogs are not Struts-dependent, so we do not explain them here For information about these dialogs, refer to “Creating a Web project” on
page 185
On the Form Field Selection page (Figure 10-22), you are asked to supply the name of the form bean from which index.jsp should get its fields, and specify which fields to use
Select the customerInfoForm form bean from the pull-down menu, select the customerNumber, and validateKey fields The customerNumber will be an input field and the validateKey a hidden field that is passed to the validation routine
Click Next
Figure 10-22 Choosing form bean fields for index.jsp
On the next dialog (see Figure 10-23) you can design the input form used on the index.jsp page Unfortunately this feature does not use the Struts tag libraries to its fullest
For example, if you enter customerNumber as the label for a field, what you really would like in the JSP is <bean:message key="customerNumber"/>, so that the corresponding text from the ApplicationResources.properties file is displayed The result produced by the wizard, however, is the exact text you
Trang 6Therefore, for the customerNumber field:
– Label: <bean:message key="prompt.enterCustomerId"/>
– Size: 20
For the validateKey field:
– Label: blank
– Initial value: 1
– Field type: hidden
Click Finish
Figure 10-23 Designing input fields
The index.jsp is created and opened in the Page Designer
As you can see in the editor, the wizard has inserted the two Struts tag libraries
we requested:
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
Trang 7It has also created an input form that prompts for the customer number and submits it to the listAccounts action for processing:
<html:form action="/listAccounts">
<TABLE border="0">
<TBODY>
<TR>
<TH></TH>
<TD><html:hidden property='validateKey' value='1' /></TD>
</TR>
<TR>
<TH><bean:message key="prompt.enterCustomerId" /></TH>
<TD><html:text property='customerNumber' size='20' value='' /></TD>
</TR>
<TR>
<TD><html:submit property="submit" value="Submit" /></TD>
<TD><html:reset /></TD>
</TR>
</TBODY>
</TABLE>
</html:form>
The Struts <html:form> tag is used to generate the body of the input form The
<html:text>, <html:submit>, and <html:reset> tags generate the fields and buttons
In the Tasks view you see an error:
Target /listAccounts does not exist in the following modules: / This is because the form’s action refers to the listAccounts action that we have not yet developed This error will be fixed when we implement listAccounts
Tailoring the JSP
The index.jsp that our application uses is a little more complex than the index.jsp page the wizard has generated for us:
This JSP defines the two Struts tag libraries that we use:
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
It then defines the start of the HTML section using the following tag:
<html:html>
Change the <TITLE> tag to:
Note: If you do not see the errors in the tasks view, it may be due to your
filtering settings in the Tasks view
Trang 8This tag takes the mandatory parameter key which refers to the message in the ApplicationResources.properties file that should be inserted The
<bean:message> tag automatically converts any non-printable characters into their HTML representation (for example, the ampersand character is
converted into &)
Under the <BODY> tag, add the RedBank text and image in the same way as in the index.html file in “Using the Page Designer” on page 196:
<TABLE border="0">
<TBODY>
<TR>
<TD>
<H1><FONT color="red">Red</FONT>Bank</H1>
</TD>
<TD><IMG border="0" src="images/itso.gif" width="50"
height="40"></TD>
</TR>
</TBODY>
</TABLE>
Add a heading 2 with:
<H2><bean:message key="text.welcome"/></H2>
After the header, you can display error messages by using the <html:errors> tag:
<html:errors></html:errors>
This tag displays the error messages returned as an ActionErrors object by a form bean’s validate method (or placed in the request scope by an action) In the ApplicationResources.properties file we have defined the following special keys that applies basic formatting for the error messages:
errors.header=<P><font color="#ff0000"><strong><ul>
errors.footer=</ul></strong></font></P>
If these two keys are present, the <html:errors> tag inserts their content just before and after the actual error messages This makes our errors appear as
an unordered list and in red color In the ApplicationResources.properties file we prefix each error message with <li> so they are displayed as a bulleted list
Tip: You can use the JSP -> Insert Custom option to select any custom tags from the Struts tag library For example, for the heading:
Select the message tag in the bean library and click Insert
In the Properties view, set the key value to text.pageTitle
Trang 9 The <html:hidden> tag is used to supply the additional validateKey parameter we need to determine which fields to validate:
<html:hidden property="validateKey" value="1"/>
The <html:text> tag is used to populate the input field with the contents of the corresponding field from the CustomerInfoForm form bean:
<html:text property="customerNumber" size="20"/>
The submit button of the form is rendered using the <html:submit> tag:
<html:submit property="submit" value="Submit" />
We can use the <bean:message> tag to supply a label from the resources:
<html:submit><bean:message key="text.submit"/></html:submit>
Add a footing after the form:
<P><bean:message key="text.footer"/></P>
The complete JSP is shown in Example 10-1
Example 10-1 Complete index.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html>
<HEAD>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="true" %>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">
<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="theme/Master.css" rel="stylesheet" type="text/css">
<TITLE><bean:message key="text.pageTitle"/></TITLE>
</HEAD>
<BODY>
<TABLE border="0">
<TBODY>
<TR>
<TD>
<H1><FONT color="red">Red</FONT>Bank</H1>
</TD>
<TD><IMG border="0" src="images/itso.gif" width="50" height="40"></TD>
</TR>
</TBODY>
</TABLE>
<H2><bean:message key="text.welcome"/></H2>
<html:errors></html:errors>
<html:form action="/listAccounts">
<TABLE border="0">
<TBODY>
Trang 10<TD><html:hidden property='validateKey' value='1' /></TD>
</TR>
<TR>
<TH><bean:message key="prompt.enterCustomerId" /></TH>
<TD><html:text property='customerNumber' size='20' value='' /></TD>
</TR>
<TR>
<TD><html:submit><bean:message key="text.submit"/></html:submit></TD>
<TD><html:reset /></TD>
</TR>
</TBODY>
</TABLE>
</html:form>
<P><bean:message key="text.footer"/></P>
</BODY>
</html:html>
Application Developer Struts tools also provide real-time rendering of the Struts tags Switch to the Design view of the Page Designer to see what the JSP will look like (Figure 10-24)
Figure 10-24 Rendering Struts tags in Design view
Save and close the index.jsp file