JaVa
   

A Sample app

In order to see how to use Struts, we will build a Web app that allows a user to log in and register using a username and password. The system will present a registration page with a form to gather a username, the password, and a copy of the password, which will be used to make sure the user typed in the right combination of characters. The registration system consists of six steps. All of the steps relate to the Struts process diagrammed above. The steps are:

  1. Create an ActionForm.

  2. Build the action.
  3. Modify the struts-config.xml file.
  4. Create an appropriate web.xml file.
  5. Create Success and Failure pages.
  6. Create a Register page.

Creating the ActionForm

As you might expect, we will use an HTML form to gather the username, password, and second password. There will need to be a way of getting the data entered by the user into the system so it can be processed. In the "old" way, we would obtain the HttpServletRequest object and use the getParameter() method to get the values. Under Struts, we will use a JavaBean for the transport object. As you learned earlier, when a user clicks a Submit button in a form, the action attribute of the <form> tag will specify a Struts action defined in the struts-config.xml file. Associated with the Struts action is an ActionForm. For our registration example, we will use the class defined in this listing:

import org.apache.struts.action.*;
public class RegisterForm extends ActionForm {
 protected String username;
 protected String password;
 protected String password2;
 public String getUsername() { return this.username; }
 public String getPassword() { return this.password; }
 public String getPassword2() { return this.password2; }
 public void setUsername(String username) { this.username = username; };
 public void setPassword(String password) { this.password = password; };
 public void setPassword2(String password) { this.password2 = password; };
}


The RegisterForm class is designed to handle all of the data that will be sent from our form. The class must inherit from ActionForm, which is a Struts base class. As you can see, the code in the class is what you would expect from a JavaBean. There are protected attributes and getter/setter methods for each of them. Both the system and the developer will use this Form class. The developer will access it from the Velocity templates here as well as in the action discussed next.

Building the Action

The action is where all of business work occurs, usually as a result of a user clicking a link or a Submit button of a form. Based on the Struts configuration file, an Action object will be put into play. The next listing shows the code for the RegisterAction class.

import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.io.*;
public class RegisterAction extends Action {

 public ActionForward perform(
ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 RegisterForm rf = (RegisterForm) form;
 String username = rf.getUsername();
 String password = rf.getPassword();
 String password2 = rf.getPassword2();
 if (password.equals(password2)) {
 try {
 return mapping.findForward("success");
 } catch(Exception e) {
 return mapping.findForward("failure");
 }
 }
 return mapping.findForward("failure");
 }
}


As you might expect, the RegisterAction class extends the Struts Action base class. The Struts system will call the perform() method providing a Form object if appropriate and the HttpServletRequest and Response objects. In our case, we immediately cast the Form class into RegisterForm and pull the values for the username, password, and second password.

The code will check to see if the two passwords match. If they do, we tell Struts to return a value of success, which is matched against the configuration file and the success.jsp template. Otherwise, a value of failure is returned for the failure.jsp template.

Configuring Struts Config

Most of the structure for a Struts Web app is found in the configuration file called struts-conf.xml, as shown in here:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN"
 "http://jakarta.apache.org/struts/dtds/
struts-config_1_0.dtd">
<struts-config>
 <form-beans>
 <form-bean type="RegisterForm"/>
 </form-beans>
 <action-mappings>
 <action path="/struts"
 type="RegisterAction"
 >
 <forward path="/success.jsp"/>
 <forward path="/failure.jsp"/>
 </action>
 </action-mappings>
</struts-config>


In the configuration file, we define the Form JavaBeans including their name, which is a reference for the <action> element, and the class name. Next, we define all of the actions that can occur in the app. We have only one, which we have called struts. When the struts action is called from a <form> or link, the framework will activate the RegisterAction action and use the RegisterForm form to pull the data from the <form> data. Also defined in the <action> element are the forwards, which represent the pages where results will be provided to the user.

Creating the Web.xml File

In addition to the Struts configuration file, we also need to include a web.xml file so the app server knows how to handle requests from the user:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
 PUBLIC "-//Oracle//DTD Web app 2.2//EN"
 "http://java.oracle.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
 <!-- Action Servlet Configuration -->
 <servlet>
 <servlet-name>action</servlet-name>
 <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
 <init-param>
 <param-name>config</param-name>
 <param-value>/WEB-INF/struts-config.xml</param-value>
 </init-param>
 <init-param>
 <param-name>debug</param-name>
 <param-value>2</param-value>
 </init-param>
 <init-param>
 <param-name>detail</param-name>
 <param-value>2</param-value>
 </init-param>
 <init-param>
 <param-name>validate</param-name>
 <param-value>true</param-value>
 </init-param>
 <load-on-startup>2</load-on-startup>
 </servlet>
 <!-- Action Servlet Mapping -->
 <servlet-mapping>
 <servlet-name>action</servlet-name>
 <url-pattern>*.do</url-pattern>
 </servlet-mapping>
 <!-- Struts Tag Library Descriptors -->
 <taglib>
 <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
 <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
 </taglib>
 <taglib>
 <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
 <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
 </taglib>
 <taglib>
 <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
 <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
 </taglib>
</web-app>


The web.xml file consists of two important parts. The first is a definition of <servlet-mapping> and <servlet> elements for Struts. The configuration says that any URL with an ending of *.do will be redirected to the ActionServlet servlet provided with Struts. The second maps all *.jsp URLs to be directed to the VelocityViewServlet.

Building the Success and Failure Pages

When a user provides a username and two passwords that match, the RegisterAction class will instruct the Struts ActionServlet to use the success forward. The success forward, defined in the Struts configuration file, tells the system to use the success.jsp JSP to display output to the user. Following is the code for the template:

<HTML>
<HEAD>
 <TITLE>Success</TITLE>
</HEAD>
<BODY>
 Registration Success!
 Thanks for logging in.
 <P><A href="register.jsp">Try Another?</A></P>
</BODY>
</HTML>


The template is fairly basic, but you get the idea. If the user is successful in providing accurate information, we will pull the username from the RegisterForm object created when the RegisterAction action was executed by Struts. The result of this page is shown here:

Java Click To expand

The Failure page is similar to the Success template but tells the user to try again.

Building the Register Page

Throughout this discussion we have referenced the page where the user can provide information and submit it to the server. The following listing shows the Register template that provides this capability.

<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<HTML> <HEAD>
<TITLE>Registration Page</TITLE>
<html:base/>
</HEAD>
<BODY>
<logic:present >
 Hello <bean:write property="username" />
</logic:present>
<html:link forward="logon">Log in</html:link>
<logic:present >
</BODY>
</HTML>


As you can see from the previous listing, we begin the code by determining if there is a user bean already stored in the current session for the user. If so, we display the name of the user and then a link to log into our system. The name of the actual login page is logon.jsp, and it is found here:

<%@ taglib uri="/tags/struts-html" prefix="html" %>
<HTML> <HEAD>
<TITLE> Register Page</TITLE>
</HEAD> <BODY>
 <html:form action="registerForm">
 <table>
 <tr>
 <td>username:</td>
 <td><html:text property="username"/></td>
 </tr>
 <tr>
 <td>password 1:</td>
 <td><html:text property="password1"/></td>
 </tr>
 <tr>
 <td>password 2:</td>
 <td><html:text property="password2"/></td>
 </tr>
 </table>
</BODY>
</HTML>


This code handles the form that will be used by the user to submit their username and two copies of their desired password. The most important part of the code is the <html:form> tag, which will use a mapping based on the registerForm entry. If you look back in the Struts configuration file, you will see that an action call to registerForm will execute the RegisterAction class.

Setup

The setup for the app is quite simple. Place all of the files based on this directory structure:

/webapps/struts
/webapps/struts/register.jsp
/webapps/struts/success.jsp
/webapps/struts/failure.jsp
/webapps/struts/WEB-INF/web.xml
/webapps/struts/WEB-INF/struts-config.xml
/webapps/struts/WEB-INF/classes/RegisterForm.java
/webapps/struts/WEB-INF/classes/RegisterAction.java
/webapps/struts/WEB-INF/lib/struts_1_0_2.jar
/webapps/struts/WEB-INF/lib/dom4j.jar
/webapps/struts/WEB-INF/lib/commons-collections.jar


Again, this structure is based on the Resin app server.

Compile

To compile the Action and Form classes, use the following command

javac "../lib/struts_1_0_2.jar;./;" *.java


or build an appropriate Ant build script. Once the .java source files have been compiled, you can restart the app server.

Run

Execute the app by browsing to the following URL or its equivalant, based on your app server:

http://localhost:8080/struts/register.jsp


You should immediately see a page asking you to log on to the system. After clicking the link, you will be presented with a form containing a username and two password fields as well as a Submit button. Enter the appropriate information in the fields and click Submit.


JaVa
   
Comments