[ Team LiB ] Previous Section Next Section

An Overview of Struts

Struts was originally written by Craig R. McClanahan of Sun Microsystems and was donated to the Apache Software Foundation in May 2000. Like other Apache Jakarta projects, Struts is open source, and developers are encouraged to contribute to its development. To use Struts, all you need to do is make sure that the struts.jar file is in your classpath (this will be discussed later in the hour). Struts provides developers with an out-of-the-box implementation of the Model-View-Controller (MVC) design pattern. It provides developers with simplified APIs and a structure that they can use to quickly start programming Web applications using JavaServer Pages and servlets in the MVC paradigm.

Figure 21.1 shows the various components on Struts as they map to the MVC design pattern.

Figure 21.1. Struts components map to the MVC architecture.

graphics/21fig01.gif

Struts Model

Action classes in Struts form the "model" in an MVC paradigm. The Controller layer (as discussed in a later section) invokes a particular action class. This action class can use different components such as JavaBeans, Enterprise JavaBeans (EJB), or other Java classes to perform business logic, persistence, and so on. We will look at action classes and the action servlet later in this hour.

The action servlet figures out which action class to call and then invokes the "execute" method on that action class. The example shown in Listing 21.1 shows a simple action class that validates the login information (username and password) for a user.

Listing 21.1 LoginUserAction.java
package examples;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LoginUserAction extends Action {

   public ActionForward execute(ActionMapping theMapping, ActionForm theForm,
                                HttpServletRequest request,
                                HttpServletResponse response)
                    throws ServletException {

        LoginUserForm userForm = (LoginUserForm) theForm;
        User user = User.findUser(userForm.getUsername());
        ActionErrors errors = new ActionErrors();

        if (user == null) {
            errors.add("username",
                       new ActionError("loginform.username.notfound"));
        }
        if (!user.getPassword().equals(userForm.getPassword()) ) {
            errors.add("password",
                       new ActionError("loginform.password.invalid"));
        }
        if (errors.size() > 0) {
            saveErrors(request, errors);
            return theMapping.getInputForward();
        }
        request.getSession().setAttribute("currentUser", user);
        return theMapping.findForward("success");
    }
}

Listing 21.2 shows the user class (User) used by the action class (LoginUserAction).

Listing 21.2 User.java
package examples;

public class User {

   private String username = null;
   private String password = null;

   public String getUsername () {
        return this.username;
   }
   public void setUsername(String _username) {
       this.username = _username;
   }

   public String getPassword () {
        return this.password;
   }
   public void setPassword(String _password) {
       this.password = _password;
   }

   public static User findUser(String username) {
       User usr = new User();
       usr.setUsername(username);
       usr.setPassword("dummy");
       return usr;
 }
}

Struts View

The "view" is generally made up of the JavaServer Pages used to present HTML screens to the client. Other technologies such as XSLT can also form "view" components. In Struts, there is also the concept of an ActionForm.

An ActionForm basically models the HTML form on the JavaServer Pages and is used as an intermediary placeholder for transferring data from the "view" to the "model." Every form element on your JavaServer Page should have a corresponding attribute in your ActionForm.

The ActionForm also performs functions such as user input validation. You need to override the "validate" method to add custom validation as shown in Listing 21.3.

The ActionErrors object is checked by the controller to see whether there are any errors. If the size of the ActionErrors object is greater than 0, then control is redirected to the error page as specified in the struts_config.xml file. We will talk about this file in detail later in this hour.

Listing 21.3 shows the ActionForm used for the login page.

Listing 21.3 LoginUserForm.java
package examples;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;

public class LoginUserForm extends ActionForm {
    private String username = null;
    private String password = null;

    public String getUsername () {
       return this.username;
    }

    public void setUsername(String _name) {
       this.username = _name;
    }

    public String getPassword () {
        return this.password;
    }

    public void setPassword(String _pass) {
      this.password = _pass;
    }

    public ActionErrors validate(ActionMapping mapping,
                                 HttpServletRequest request)  {
        ActionErrors errors = new ActionErrors();

        if (null == this.username) {
            errors.add("Username",
                       new ActionError("LoginForm.username.required"));
        }
        if (null == this.password) {
            errors.add("Password",
                       new ActionError("LoginForm.password.required"));
        }
        return errors;
    }
}

DynaForms

graphics/bytheway_icon.gif

There is new concept in Struts called DynaForms that saves you from having to create these ActionForms for each JavaServer Page or action. This is still in very early stages and thus we will not be covering it in this book. You should read more about these on the Apache Struts site at http://jakarta.apache.org/struts.


Struts also comes with a rich set of tag libraries to provide functionality on the JavaServer Page. Listing 21.4 shows a JavaServer Page that can be used to log in the user. Notice the use of the struts-html.tld. This provides Struts-related HTML functionality such as the html:errors and the HTML form tags. Struts also offers the following tag libraries:

  • HTML, for dealing with HTML components, such as Forms and Textboxes

  • Logic, for conditional display and iteration

  • Bean, for data access

  • Nested, for access to the properties of beans

  • Tiles, for layout of pages

Struts has made it very easy to use these tag libraries directly from the Apache site. This will allow you to work with these tag libraries without having to modify your web.xml file or copy these tag libraries to your server. To leverage the tag libraries, you can add the following line of code to your JSP:


<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>

The other option is to copy the tag libraries to your WEB-INF folder and reference the tag libraries in your JavaServer Page as shown in Listing 21.4.

Using the JSTL libraries

graphics/bytheway_icon.gif

Except for the Struts HTML and Tiles tag libraries, all the others have been replaced by JSTL. If you are using a Servlet 2.3 container or later, you should use the JSTL libraries instead of the Struts ones.


Listing 21.4 shows the JSP used to get the login information for a user.

Listing 21.4 loginPage.jsp
<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<head>
    <title>Login Page</title>
</head>

<h1>Login Page</h1>
<html:form action="/login">
    <html:errors property="Username"/>
    <BR>
    Username: <html:text property="Username"/>
    <BR>
    <html:errors property="Password"/>
    <BR>
    Username: <html:password property="Password"/>
    <BR>
    <html:submit/>
</html:form>

Struts Controller

Struts implements the Front Controller design pattern. The controller processes all HTTP requests and determines what to do next. It controls the interaction between the Model and View layers. To do this, it uses a configuration file to store all the mappings for your application. An example of the struts-config.xml file is shown in Listing 21.5. This can be used for the login example that we have been building in this hour.

Listing 21.5 shows the struts-config.xml file for the login page.

Listing 21.5 struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>

  <form-beans>
    <form-bean name="loginUserForm" type="jspbook.LoginUserForm"/>
  </form-beans>

  <action-mappings>
    <action path="/login" name="loginUserForm" scope="request" validate="true"
            type="jspbook.LoginUserAction"
            input="/loginPage.jsp">
       <forward name="success" path="/mainMenu.jsp"/>
    </action>
  </action-mappings>

</struts-config>

Form beans define a name that Struts uses to access an ActionForm. Actions define the URL that the action is associated to. They also provide the input, resulting, and error JSPs. Lastly, you specify whether you want to validate this form or not.

The basic code snippets you have seen so far show you all the elements you need to create a simple Struts application. However, you still need to set up your servlet container to work with Struts. You learn how to do this in the next section.

Getting the Struts User Guide

graphics/bytheway_icon.gif

The Struts page on the Apache Web site has very extensive documentation and examples that will help you master the more advanced concepts of Struts. Look at the Struts user guide at

http://jakarta.apache.org/struts/userGuide/index.html


    [ Team LiB ] Previous Section Next Section