Friday, January 2, 2009

Struts Tutorials - Jakarta Struts Tutorial

This complete reference of Jakarta Struts shows you how to develop Struts applications using ant and deploy on the JBoss Application Server. Ant script is provided with the example code. Many advance topics like Tiles, Struts Validation Framework, Java Script validations are covered in this tutorial.

  1. Introduction to the Apache Struts
    This lesson is an introduction to the Struts and its architecture.
  2. MVC Architecture
    The main aim of the MVC architecture is to separate the business logic and application data from the presentation data to the user.
  3. Struts Architecture
    Struts is an open source framework used for developing J2EE web applications using Model View Controller (MVC) design pattern. It uses and extends the Java Servlet API to encourage developers to adopt an MVC architecture.
  4. How Struts Works?
    The basic purpose of the Java Servlets in struts is to handle requests made by the client or by web browsers. In struts JavaServerPages (JSP) are used to design the dynamic web pages. In struts, servlets helps to route request which has been made by the web browsers to the appropriate ServerPage.
  5. Introduction to the Struts Controller
    This lesson is an introduction to Controller part of the Struts Framework.
  6. Introduction to the Struts Action Class
    This lesson is an introduction to Action Class of the Struts Framework.
  7. Using Struts ActionFrom Class
    This shows how to create user interface form using struts ActionFrom class and jsp page.
  8. Using Struts HTML Tags
    Section shows you the different types of Struts HTML Tags available for the development of views in JSP.
  9. Introduction to Struts Validator Framework
    Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side.
  10. Client Side Address Validation in Struts
    In this lesson we will create JSP page for entering the address and use the functionality provided by Validator Framework to validate the user data on the browser.
  11. Custom Validators Example
    In this tutorial you will learn how to develop Custom Validators in your Struts 1.3 applications. Struts Validator framework provides many validation rules that can be used in the web applications. If you application needs special kind of validation, then you can extend the validator framework to develop your own validation rule.
  12. Developing Application with Struts Tiles
    In this lesson we will create Struts Tiles Applications.
  13. Using tiles-defs.xml in Tiles Application
    In this lesson you will learn how to define and use the "plugin" definitation in tiles-defs.xml file.

    Advance Struts
  14. Struts DynaActionForm
    In this lesson we will create Struts DynaActionForm.
  15. Struts File Upload
    In this lesson we will create Struts File Upload program.
  16. Struts file upload and save on server
    In this tutorial you will learn how to use Struts program to upload on the Server and display a link to the user to download the uploaded file .

    Struts Actions Examples
  17. Struts Built-In Actions
    In this section we will give a quick look to the few of built-in utility actions shipped with Struts APIs. These built-in utility actions provide different functionalities useful to diverse applications.
  18. Struts Dispatch Action Example
    Here in this example you will learn more about Struts Dispatch Action that will help you grasping the concept better.
  19. Struts Forward Action
    In this section we will learn about Struts ForwardAction (org.apache.struts.actions.ForwardAction). The ForwardAction is one of the Built-in Actions that is shipped with struts framework.
  20. Struts LookupDispatchAction Example
    Struts LookupDispatch Action
    (org.apache.struts.actions.LookupDispatchAction) is one of the Built-in Actions provided along with the struts framework.
  21. Struts MappingDispatchAction Example
    Struts MappingDispatch Action
    (org.apache.struts.actions.MappingDispatchAction) is one of the Built-in Actions provided along with the struts framework.
  22. STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS
    In this article we will see how to achieve this. Struts provides four important classes for this
    purpose.
  23. Aggregating Actions In Struts Revisited
    An action aggregation is a grouping of a set of related actions into a single unified action in order to eliminate the need to write a new action class for every action. In this part, I will walk through a full-fledged practical example of each of the types presented in Part I namely the DispatchAction , LookupDispatchAction , MappingDispatchAction and ActionDispatcher along with two new aggregations which slightly differ in syntax but are more efficient than the previous ones.
  24. Set the mapping name example
    Set the mapping name to the action attribute of html:link
  25. Set the action name example
    Set the action name to the action attribute of html:link
  26. Configuring Struts DataSource Manager on Tomcat 5
    In this lesson we will create example to Configure Struts DataSource Manager on Tomcat

Introduction to the Apache Struts

This tutorial is extensive guide to the Struts Framework. In this tutorial you will learn how to develop robust application using Jakarta Struts Framework. This tutorial assumes that the reader is familiar with the web application development with JSP, Servlets, JDBC and custom tags. To begin with let's understand the Jakarta Struts Framework.

What is Struts?

Struts Frame work is the implementation of Model-View-Controller (MVC) design pattern for the JSP. Struts is maintained as a part of Apache Jakarta project and is open source. Struts Framework is suited for the application of any size. Latest version of struts can be downloaded from http://jakarta.apache.org/. We are using jakarta-struts-1.1 and jakarta-tomcat-5.0.4 for this tutorial.

What is Model-View-Controller (MVC) Architecture?

Model-View-Controller architecture is all about dividing application components into three different categories Model, View and the Controller. Components of the MVC architecture has unique responsibility and each component is independent of the other component. Changes in one component will have no or less impact on other component. Responsibilities of the components are:

Model: Model is responsible for providing the data from the database and saving the data into the data store. All the business logic are implemented in the Model. Data entered by the user through View are check in the model before saving into the database. Data access, Data validation and the data saving logic are part of Model.

View: View represents the user view of the application and is responsible for taking the input from the user, dispatching the request to the controller and then receiving response from the controller and displaying the result to the user. HTML, JSPs, Custom Tag Libraries and Resources files are the part of view component.

Controller: Controller is intermediary between Model and View. Controller is responsible for receiving the request from client. Once request is received from client it executes the appropriate business logic from the Model and then produce the output to the user using the View component. ActionServlet, Action, ActionForm and struts-config.xml are the part of Controller.

Setting Up Development Environment

Installing JDK:

Download JDK 1.4 or above from sun site. Follow the instruction given in the installation manual and install JDK.

Installing Tomcat:

Download Tomcat from the apache site and install it. I have downloaded jakarta-tomcat-5.0.4 and installed for this tutorial. To test your installation go to your installation directory/bin and issue startup command to run the server. Open browser and type http://localhost:8080/ to test the server. It should display the welcome page. If not consult tomcat documentation before going further.

Installing Struts Application:

Download latest version of Struts from the official site of Struts http://jakarta.apache.org/struts. Extract the file ito your favorite directory and copy struts-blank.war, struts-documentation.war and struts-example.war from "jakarta-struts-1.1\webapps" directtory into "jakarta-tomcat-5.0.4\webapps" directory.

struts-blank.war is the blank struts application which is useful in creating struts application from scratch. We will use this file to create our web application.

struts-documentation.war contains API and important documents for the struts application development.

struts-example.war is simple MailReader Demonstration Application.

MVC Architecture

The main aim of the MVC architecture is to separate the business logic and application data from the presentation data to the user.

Here are the reasons why we should use the MVC design pattern.

  1. They are resuable : When the problems recurs, there is no need to invent a new solution, we just have to follow the pattern and adapt it as necessary.
  2. They are expressive: By using the MVC design pattern our application becomes more expressive.

1). Model: The model object knows about all the data that need to be displayed. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application. The model represents enterprise data and the business rules that govern access to and updates of this data. Model is not aware about the presentation data and how that data will be displayed to the browser.

2). View : The view represents the presentation of the application. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it. The view is not dependent on the application logic. It remains same if there is any modification in the business logic. In other words, we can say that it is the responsibility of the of the view's to maintain the consistency in its presentation when the model changes.

3). Controller: Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. In GUIs, the views and the controllers often work very closely together.

Difference between Model 1 and Model 2 architecture:

Features of MVC1:

  1. Html or jsp files are used to code the presentation. To retrieve the data JavaBean can be used.
  2. In mvc1 archictecture all the view, control elements are implemented using Servlets or Jsp.
  3. In MVC1 there is tight coupling between page and model as data access is usually done using Custom tag or through java bean call.

Features of MVC2:

  1. The MVC2 architecture removes the page centric property of MVC1 architecture by separating Presentation, control logic and the application state.
  2. In MVC2 architecture there is only one controller which receives all the request for the application and is responsible for taking appropriate action in response to each request.

What is Struts - Struts Architecture

In this section we will discuss about Architecture. Struts is famous for its robust Architecture and it is being used for developing small and big software projects.

Struts is an open source framework used for developing J2EE web applications using Model View Controller (MVC) design pattern. It uses and extends the Java Servlet API to encourage developers to adopt an MVC architecture. Struts framework provides three key components:

  1. A request handler provided by the application developer that is used to mapped to a particular URI.
  2. A response handler which is used to transfer the control to another resource which will be responsible for completing the response.
  3. A tag library which helps developers to create the interactive form based applications with server pages.

Struts provides you the basic infrastructure infrastructure for implementing MVC allowing the developers to concentrate on the business logic.

MVC Architecture

The main aim of the MVC architecture is to separate the business logic and application data from the presentation data to the user.

Here are the reasons why we should use the MVC design pattern.

  1. They are resuable : When the problems recurs, there is no need to invent a new solution, we just have to follow the pattern and adapt it as necessary.
  2. They are expressive: By using the MVC design pattern our application becomes more expressive.

1). Model: The model object knows about all the data that need to be displayed. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application. The model represents enterprise data and the business rules that govern access to and updates of this data. Model is not aware about the presentation data and how that data will be displayed to the browser.

2). View : The view represents the presentation of the application. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it. The view is not dependent on the application logic. It remains same if there is any modification in the business logic. In other words, we can say that it is the responsibility of the of the view's to maintain the consistency in its presentation when the model changes.

3). Controller: Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. In GUIs, the views and the controllers often work very closely together.

Overview of the Struts Framework

The Struts framework is composed of approximately 300 classes and interfaces which are organized in about 12 top level packages. Along with the utility and helper classes framework also provides the classes and interfaces for working with controller and presentation by the help of the custom tag libraries. It is entirely on to us which model we want to choose. The view of the Struts architecture is given below:

The Struts Controller Components:

Whenever a user request for something, then the request is handled by the Struts Action Servlet. When the ActionServlet receives the request, it intercepts the URL and based on the Struts Configuration files, it gives the handling of the request to the Action class. Action class is a part of the controller and is responsible for communicating with the model layer.

The Struts View Components:

The view components are responsible for presenting information to the users and accepting the input from them. They are responsible for displaying the information provided by the model components. Mostly we use the Java Server Pages (JSP) for the view presentation. To extend the capability of the view we can use the Custom tags, java script etc.

The Struts model component:

The model components provides a model of the business logic behind a Struts program. It provides interfaces to databases or back- ends systems. Model components are generally a java class. There is not any such defined format for a Model component, so it is possible for us to reuse Java code which are written for other projects. We should choose the model according to our client requirement.

How Struts Works

The basic purpose of the Java Servlets in struts is to handle requests made by the client or by web browsers. In struts JavaServerPages (JSP) are used to design the dynamic web pages. In struts, servlets helps to route request which has been made by the web browsers to the appropriate ServerPage. The use of servlet as a router helps to make the web applications easier to design, create, and maintain. Struts is purely based on the Model- View- Contoller (MVC) design pattern. It is one of the best and most well developed design patterns in use. By using the MVC architecture we break the processing in three sections named Model, the View, and the Controller. Below we are describing the working of struts.

  1. As we all are well aware of the fact that each application we develop has a deployment descriptor i.e. WEB-INF/web.xml. This is the file which the container reads. This file has all the configuration information which we have defined for our web application. The configuration information includes the index file, the default welcome page, the mapping of our servlets including path and the extension name, any init parameters, information related to the context elements.
    In the file WEB-INF/web.xml of struts application we need to configure the Struts ActionServlet which handles all the request made by the web browsers to a given mapping. ActionServlet is the central component of the Struts controller. This servlet extends the HttpServlet. This servlet basically performs two important things. First is : When the container gets start, it reads the Struts Configuration files and loads it into memory in the init() method. You will know more about the Struts Configuration files below. Second point is: It intercepts the HTTP request in the doGet() and doPost() method and handles it appropriately.
  2. In struts application we have another xml file which is a Struts configuration file named as struts.config.xml. The name of this file can be changed. The name of the struts configuration file can be configured in the web.xml file. This file is placed under the WEB-INF directory of the web application. It is an XML document that describes all or part of Struts application. This file has all the information about many types of Struts resources and configures their interaction. This file is used to associate paths with the controller components of your application., known as Action classes like . This tag tells the Struts ActionServlet that whenever the incoming request is http://myhost/myapp/login.do, then it must invoke the controller component LoginAction. Above, you can see that we have written .do in the URL. This mapping is done to tell the web application that whenever a request is received with the .do extension then it should be appended to the URL.
  3. For each action we also have to configure Struts with the names of the resulting pages that will be shown as a result of that action. In our application there can be more than one view which depends on the result of an action. One can be for a success and the other for the failure. If the result action is "success" then the action tells the ActionServlet that the action has been successfully accomplished or vice- versa. The struts knows how to forward the specific page to the concerned destination. The model which we want to use is entirely to you, the model is called from within the controller components.
  4. Action can also get associate with a JavaBean in our Struts configuration file. Java bean is nothing but a class having getter and setter methods that can be used to communicate between the view and the controller layer. These java beans are validated by invoking the validate() method on the ActionForm by the help of the Struts system. The client sends the request by the normal form submission by using Get or Post method, and the Struts system updates that data in the Bean before calling the controller components.
  5. The view we use in the struts can be either Jsp page, Velocity templates, XSLT pages etc. In struts there are set of JSP tags which has been bundled with the struts distribution, but it is not mandatory to use only Jsp tags, even plain HTML files can be used within our Struts application but the disadvantage of using the html is that it can't take the full advantage of all the dynamic features provided in the struts framework.
    The framework includes a set of custom tag libraries that facilitate in creating the user interfaces that can interact gracefully with ActionForm beans. The struts Jsp taglibs has a number of generic and struts specific tags tags which helps you to use dynamic data in your view. These tags helps us to interact with your controller without writing much java code inside your jsp. These tags are used create forms, internally forward to other pages by interacting with the bean and helps us to invoke other actions of the web application.
    There are many tags provided to you in the struts frameworks which helps you in sending error messages, internationalization etc.

Note: The points we have described above will be in effect if and only if when the ActionServlet is handling the request. When the request is submitted to the container which call the ActionServlet, make sure that the extension of the file which we want to access should have the extension .do.

Struts working:

Process flow:

web.xml : Whenever the container gets start up the first work it does is to check the web.xml file and determine what struts action Servlets exist. The container is responsible for mapping all the file request to the correct action Servlet.

A Request : This is the second step performed by the container after checking the web.xml file. In this the user submits a form within a browser and the request is intercepted by the controller.

The Controller : This is the heart of the container. Most Struts application will have only one controller that is ActionServlet which is responsible for directing several Actions. The controller determines what action is required and sends the information to be processed by an action Bean. The key advantage of having a controller is its ability to control the flow of logic through the highly controlled, centralized points.

struts.config.xml : Struts has a configuration file to store mappings of actions. By using this file there is no need to hard code the module which will be called within a component. The one more responsibility of the controller is to check the struts.config.xml file to determine which module to be called upon an action request. Struts only reads the struts.config.xml file upon start up.

Model : The model is basically a business logic part which takes the response from the user and stores the result for the duration of the process. This is a great place to perform the preprocessing of the data received from request. It is possible to reuse the same model for many page requests. Struts provides the ActionForm and the Action classes which can be extended to create the model objects.

View : The view in struts framework is mainly a jsp page which is responsible for producing the output to the user.

Struts tag libraries : These are struts components helps us to integrate the struts framework within the project's logic. These struts tag libraries are used within the JSP page. This means that the controller and the model part can't make use of the tag library but instead use the struts class library for strut process control.

Property file : It is used to store the messages that an object or page can use. Properties files can be used to store the titles and other string data. We can create many property files to handle different languages.

Business objects : It is the place where the rules of the actual project exists. These are the modules which just regulate the day- to- day site activities.

The Response : This is the output of the View JSP object.

Understanding Struts Controller

In this section I will describe you the Controller part of the Struts Framework. I will show you how to configure the struts-config.xml file to map the request to some destination servlet or jsp file.

The class org.apache.struts.action.ActionServlet is the heart of the Struts Framework. It is the Controller part of the Struts Framework. ActionServlet is configured as Servlet in the web.xml file as shown in the following code snippets.



action
org.apache.struts.action.ActionServlet

config
/WEB-INF/struts-config.xml


debug
2


detail
2

2

This servlet is responsible for handing all the request for the Struts Framework, user can map the specific pattern of request to the ActionServlet. tag in the web.xml file specifies the url pattern to be handled by the servlet. By default it is *.do, but it can be changed to anything. Following code form the web.xml file shows the mapping.



action
*.do

The above mapping maps all the requests ending with .do to the ActionServlet. ActionServlet uses the configuration defined in struts-config.xml file to decide the destination of the request. Action Mapping Definitions (described below) is used to map any action. For this lesson we will create Welcome.jsp file and map the "Welcome.do" request to this page.

Welcome.jsp

<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>


<bean:message key="welcome.title">



<h3>



Forwarding the Welcome.do request to Welcome.jsp

The "Action Mapping Definitions" is the most important part in the struts-config.xml. This section takes a form defined in the "Form Bean Definitions" section and maps it to an action class.

Following code under the tag is used to forward the request to the Welcome.jsp.

path="/Welcome"
forward="/pages/Welcome.jsp"/>

To call this Welcome.jsp file we will use the following code.

<html:link page="/Welcome.do">First Request to the controller

Once the use clicks on on First Request to the controller link on the index page, request (for Welcome.do) is sent to the Controller and the controller forwards the request to Welcome.jsp. The content of Welcome.jsp is displayed to the user.

Understanding Struts Action Class

In this lesson I will show you how to use Struts Action Class and forward a jsp file through it.

What is Action Class?

An Action class in the struts application extends Struts 'org.apache.struts.action.Action" Class. Action class acts as wrapper around the business logic and provides an inteface to the application's Model layer. It acts as glue between the View and Model layer. It also transfers the data from the view layer to the specific business process layer and finally returns the procssed data from business layer to the view layer.

An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it. Then the struts controller (ActionServlet) slects an appropriate Action and creates an instance if necessary, and finally calls execute method.

To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class don't add the business process logic, instead move the database and business process logic to the process or dao layer.

The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

Developing our Action Class?

Our Action class (TestAction.java) is simple class that only forwards the TestAction.jsp. Our Action class returns the ActionForward called "testAction", which is defined in the struts-config.xml file (action mapping is show later in this page). Here is code of our Action Class:

TestAction.java

package roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}


Understanding Action Class
Here is the signature of the Action Class.

public ActionForward execute(ActionMapping mapping,
                             ActionForm form,
                             javax.servlet.http.HttpServletRequest request,
                             javax.servlet.http.HttpServletResponse response)
                      throws java.lang.Exception

Action Class process the specified HTTP request, and create the corresponding HTTP response (or forward to another web component that will create it), with provision for handling exceptions thrown by the business logic. Return an ActionForward instance describing where and how control should be forwarded, or null if the response has already been completed.

Parameters:

mapping - The ActionMapping used to select this instance

form - The optional ActionForm bean for this request (if any)

request - The HTTP request we are processing

response - The HTTP response we are creating

Throws:

Action class throws java.lang.Exception - if the application business logic throws an exception

Adding the Action Mapping in the struts-config.xml
To test the application we will add a link in the index.jsp
Test the Action

Following code under the tag is used to for mapping the TestAction class.

   
      path="/TestAction"
      type="roseindia.net.TestAction">
      
                

To test the new application click on Test the Action link on the index page. The content of TestAction.jsp should be displayed on the user browser.

In this lesson you learned how to create Action Class and add the mappings in the struts-config.xml. Our Action Class returns the ActionForward mapping of the TestAction.jsp.

The ActionForm Class

In this lesson you will learn about the ActionForm in detail. I will show you a good example of ActionForm. This example will help you understand Struts in detail. We will create user interface to accept the address details and then validate the details on server side. On the successful validation of data, the data will be sent to model (the action class). In the Action class we can add the business processing logic but in this case we are just forwarding it to the sucess.jsp.

What is ActionForm?
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

We will first create the class AddressForm which extends the ActionForm class. Here is the code of the class:

AddressForm.java

package roseindia.net;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.*;


/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email roseindia_net@yahoo.com
*/

/**
* Form bean for the Address Entry Screen.
*
*/
public class AddressForm extends ActionForm
{
private String name=null;
private String address=null;
private String emailAddress=null;

public void setName(String name){
this.name=name;
}

public String getName(){
return this.name;
}

public void setAddress(String address){
this.address=address;
}

public String getAddress(){
return this.address;
}


public void setEmailAddress(String emailAddress){
this.emailAddress=emailAddress;
}

public String getEmailAddress(){
return this.emailAddress;
}


/**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.name=null;
this.address=null;
this.emailAddress=null;
}

/**
* Reset all properties to their default values.
*
* @param mapping The mapping used to select this instance
* @param request The servlet request we are processing
* @return errors
*/
public ActionErrors validate(
ActionMapping mapping, HttpServletRequest request ) {
ActionErrors errors = new ActionErrors();

if( getName() == null || getName().length() <>
errors.add("name",new ActionMessage("error.name.required"));
}
if( getAddress() == null || getAddress().length() <>
errors.add("address",new ActionMessage("error.address.required"));
}
if( getEmailAddress() == null || getEmailAddress().length() <>
errors.add("emailaddress",new ActionMessage("error.emailaddress.required"));
}

return errors;
}

}

The above class populates the Address Form data and validates it. The validate() method is used to validate the inputs. If any or all of the fields on the form are blank, error messages are added to the ActionMapping object. Note that we are using ActionMessage class, ActionError is now deprecated and will be removed in next version.

Now we will create the Action class which is the model part of the application. Our action class simply forwards the request the Success.jsp. Here is the code of the AddressAction class:

AddressAction.java

package roseindia.net;

/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email roseindia_net@yahoo.com
*/

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class AddressAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("success");
}
}

Now we have to create an entry for form bean in the struts-config.xml. Add the following lines in the struts-config.xml file:

name="AddressForm"
type="roseindia.net.AddressForm"/>

Add the following line in the struts-config.xml file for handling the action "/Address.do":

path="/Address"
type="roseindia.net.AddressAction"
name="AddressForm"
scope="request"
validate="true"
input="/pages/Address.jsp">

Now create Address.jsp, which is our form for entering the address details. Code for Address.jsp is as follows:

Address.jsp

   <%@ taglib uri="/tags/struts-bean" prefix="bean" %>
   <%@ taglib uri="/tags/struts-html" prefix="html" %>
  
   
 
   
 
   <bean:message key="welcome.title">
 
   
 
   
 
   
 
   
 
   
 
   
 
        
 
          
               
          
          
        
        
          
          
        
 
        
          
          
        
               
          
          
        
  
                               Please Enter the Following Details
               
            Name
          
            
          
            Address
          
            
          
            E-mail address
          
            
          
            Save
          
            Cancel
          
   
   
   

User enter the values in the form and click on the submit form. Form validation is done on the server side and error message is displays on the jsp page. To display the error on the jsp page tag is used. The tag displays all the errors in one go. To create text box is used in jsp page.

e.g.

Above tag creates text box for entering the address. The address is retrieved from and later stored in the property named address in the form-bean. The tag Save creates the submit button and the tag Cancel is used to create the Cancel button.

Add the following line in the index.jsp to create a link for testing the Address.jsp form:

Test the Address Form

Build the application and click on the Test the Address Form link on the index page to test the newly created screen. You should see the following screen.

In this lesson you learned how to create data entry form using struts, validate and finally send process the business logic in the model part of the struts.

Struts HTML Tags

Struts provides HTML tag library for easy creation of user interfaces. In this lesson I will show you what all Struts HTML Tags are available to the JSP for the development of user interfaces.

To use the Struts HTML Tags we have to include the following line in our JSP file:

<%@ taglib uri="/tags/struts-html" prefix="html" %>

above code makes available the tag to the jsp.

Struts HTML Tags

Looks up the message corresponding to the given key in the message resources and displays it.

Tag creates the password field. The string is stored in the property named prop in the form bean.

Tag creates the text field. The string is retrieved from and later stored in the property named text1 in the form bean.

Submit

Tag creates a submit button with the provided content as the button text.

Reset

Tag creates a reset button with the provided content as the button text.

Tag prints all the available error on the page.

Tag creates the file upload element on the form. The property must be of the type org.apache.struts.upload.FormFile.

Tag creates check box on the form.

Tag creates the hidden html element on the form.

Tag creates the check box on the form.

Tag creates list box on the form. The property selectBox must be an array of supported data-types, and the user may select several entries. Use to specify the entries.

Tag creates the text area on the form.

Tag is used to create the HTML Form for posting the data on the server.

Tag generates the base tag. tells the browser to pretend that the current page is located at some URL other than where the browser found it. Any relative reference will be calculated from the URL given by instead of the actual URL. goes in the section.

Tag renders an HTML Element.

In the Address.jsp we have used some of the above tags. In the future sections I will show you more examples of the Struts HTML tags.

Struts Validator Framework

This lesson introduces you the Struts Validator Framework. In this lesson you will learn how to use Struts Validator Framework to validate the user inputs on the client browser.

Introduction to Validator Framework

Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. Server side validation of the form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

Using Validator Framework

Validator uses the XML file to pickup the validation rules to be applied to an form. In XML validation requirements are defined applied to a form. In case we need special validation rules not provided by the validator framework, we can plug in our own custom validations into Validator.

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

Structure of validator-rule.xml

The validation-rules.xml is provided with the Validator Framework and it declares and assigns the logical names to the validation routines. It also contains the client-side javascript code for each validation routine. The validation routines are java methods plugged into the system to perform specific validations.

Following table contains the details of the elements in this file:

Element

Attributes and Description

form-validation

This is the root node. It contains nested elements for all of the other configuration settings.

global

The validator details specified within this, are global and are accessed by all forms.

validator

The validator element defines what validators objects can be used with the fields referenced by the formset elements.

The attributes are:

· name: Contains a logical name for the validation routine

· classname: Name of the Form Bean class that extends the subclass of ActionForm class

· method: Name of the method of the Form Bean class

· methodParams: parameters passed to the method

· msg:Validator uses Struts' Resource Bundle mechanism for externalizing error messages. Instead of having hard-coded error messages in the framework, Validator allows you to specify a key to a message in the ApplicationResources.properties file that should be returned if a validation fails. Each validation routine in the validator-rules.xml file specifies an error message key as value for this attribute.

· depends: If validation is required, the value here is specified as 'required' for this attribute.

· jsFunctionName: Name of the javascript function is specified here.

javascript

Contains the code of the javascript function used for client-side validation. Starting in Struts 1.2.0 the default javascript definitions have been consolidated to commons-validator. The default can be overridden by supplying a element with a CDATA section, just as in struts 1.1.

The Validator plug-in (validator-rules.xml) is supplied with a predefined set of commonly used validation rules such as Required, Minimum Length, Maximum length, Date Validation, Email Address validation and more. This basic set of rules can also be extended with custom validators if required.

Structure of validation.xml

This validation.xml configuration file defines which validation routines that is used to validate Form Beans. You can define validation logic for any number of Form Beans in this configuration file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.

Element

Attributes and Description

form-validation

This is the root node. It contains nested elements for all of the other configuration settings

global

The constant details are specified in element within this element.

constant

Constant properties are specified within this element for pattern matching.

constant-name

Name of the constant property is specified here

constant-value

Value of the constant property is specified here.

formset

This element contains multiple

elements

form

This element contains the form details.
The attributes are:
name
:Contains the form name. Validator uses this logical name to map the validations to a Form Bean defined in the struts-config.xml file

field

This element is inside the form element, and it defines the validations to apply to specified Form Bean fields.

The attributes are:

· property: Contains the name of a field in the specified Form Bean

· depends: Specifies the logical names of validation routines from the validator-rules.xml file that should be applied to the field.

arg

A key for the error message to be thrown incase the validation fails, is specified here

var

Contains the variable names and their values as nested elements within this element.

var-name

The name of the criteria against which a field is validated is specified here as a variable

var-value

The value of the field is specified here

Example of form in the validation.xml file:



depends="required">


depends="required,mask">


mask
^[0-9a-zA-Z]*$


The tag to allow front-end validation based on the xml in validation.xml. For example the code: generates the client side java script for the form "logonForm" as defined in the validation.xml file. The when added in the jsp file generates the client site validation script.

In the next lesson we will create a new form for entering the address and enable the client side java script with the Validator Framework.

Client Side Address Validation in Struts

In this lesson we will create JSP page for entering the address and use the functionality provided by Validator Framework to validate the user data on the browser. Validator Framework emits the JavaScript code which validates the user input on the browser. To accomplish this we have to follow the following steps:

  1. Enabling the Validator plug-in: This makes the Validator available to the system.
  2. Create Message Resources for the displaying the error message to the user.
  3. Developing the Validation rules We have to define the validation rules in the validation.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation.
  4. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript.
  5. Build and test: We are required to build the application once the above steps are done before testing.

Enabling the Validator plug- in
To enable the validator plug-in open the file struts-config.xml and make sure that following line is present in the file.


apache.struts.validator.ValidatorPlugIn">
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>

Creating Message Resources
Message resources are used by the Validator Framework to generate the validation error messages. In our application we need to define the messages for name, Address and E-mail address. Open the Struts\strutstutorial\web\WEB-INF\MessageResources.properties file and add the following lines:
AddressForm.name=Name
AddressForm.address=Address
AddressForm.emailAddress=E-mail address

Developing Validation rules
In this application we are adding only one validation that the fields on the form should not be blank. Add the following code in the validation.xml.



depends="required">


depends="required">


depends="required">


The above definition defines the validation for the form fields name, address and emailAddress. The attribute depends="required" instructs the Validator Framework to generate the JavaScript that checks that the fields are not left blank. If the fields are left blank then JavaScript shows the error message. In the error message the message are taken from the key defined in the key=".."/> tag. The value of key is taken from the message resources (Struts\strutstutorial\web\WEB-INF\MessageResources.properties).

Applying Validation rules to JSP
Now create the AddressJavascriptValidation.jsp file to test the application. The code for AddressJavascriptValidation.jsp is as follows:

<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>



<bean:message key="welcome.title">







This application shows the use of Struts Validator.

The following form contains fields that are processed by Struts Validator.

Fill in the form and see how JavaScript generated by Validator Framework validates the form.





























<font size="4">Please Enter the Following Details

Name



Address



E-mail address



Save

Cancel









The code is used to plug-in the Validator JavaScript.

Create the following entry in the struts-config.xml for the mapping the /AddressJavascriptValidation url for handling the form submission through AddressJavascriptValidation.jsp.

path="/AddressJavascriptValidation"
type="roseindia.net.AddressAction"
name="AddressForm"
scope="request"
validate="true"
input="/pages/AddressJavascriptValidation.jsp">

Add the following line in the index.jsp to call the form.


  • /pages/AddressJavascriptValidation.jsp">Client Side Validation for Address Form


    The Address Form that validates the data on the client side using Stuts Validator generated JavaScript.
  • Building Example and Testing

    To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the AddressJavascriptValidation.jsp page. Your browser should show the following out put.

    If the fields are left blank and Save button is clicked, browser shows the error message.

    In this lesson you learned how to use Struts Validator Framework to validate the form on client browser.

    Creating Custom Validators in STRUTS

    In this tutorial you will learn how to develop Custom Validators in your Struts 1.3 applications. Struts Validator framework provides many validation rules that can be used in the web applications. If you application needs special kind of validation, then you can extend the validator framework to develop your own validation rule.

    The client-side validation in Struts is well known. Here are some of the available features:

    • required
    • requiredif
    • validwhen
    • minlength
    • maxlength
    • mask
    • byte
    • short
    • integer
    • long
    • float
    • double
    • byteLocale
    • shortLocale
    • integerLocale
    • longLocale
    • floatLocale
    • doubleLocale
    • date
    • intRange
    • longRange
    • floatRange
    • doubleRange
    • creditCard
    • email
    • url

    These are found in the validator-rules.xml inside the tags. The validator-rules.xml file is found in the commons-validator jar.

    Let us know create a new validator for entering the name field of a form. The form should accept only "administrator" for the name field. To accomplish this edit the validator-rules.xml and add the following code under the tag:

    classname="org.apache.struts.validator.FieldChecks"
    method="validateName"
    methodParams="java.lang.Object,
    org.apache.commons.validator.ValidatorAction,
    org.apache.commons.validator.Field,
    org.apache.struts.action.ActionMessages,
    org.apache.commons.validator.Validator,
    javax.servlet.http.HttpServletRequest"
    msg="errors.name">
    <javascript> function validateName(form) {
    var isValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();

    var omatchName= eval('new ' + jcv_retrieveFormName(form) + '_matchname() ');

    for (var x in omatchName) {
    if (!jcv_verifyArrayElement(x, omatchName[x])) {
    continue;
    }
    var field = form[omatchName[x][0]];

    if (!jcv_isFieldPresent(field)) {
    fields[i++] = omatchName[x][1];
    isValid=false;
    } else if (field.value != "administrator") {
    fields[i++]=omatchName[x][1];
    isValid=false;
    }
    }

    if (fields.length > 0) {
    jcv_handleErrors(fields, focusField);
    }
    return isValid;
    }
    ]]>

    To understand the above code:

    • matchname is the new validator we are creating; use can use anything you want (e.g. matchAdmin) remembering that this will be used in another file which will be described later
    • the error message issued in the browser has the key errors.name; you can have any name here like errors.admin; once again this will be explained later
    • the Java Script function to call is declared in the method attribute of the validator tag; in the above it is called validateName; you can have any valid Java Script function name (e.g. validateAdmin)
    • the Java Script to process this tag is declared inside CDATA; note that the function name should match EXACTLY with the name declared in the method attribute of the validator tag
    • the field.value != "administrator" is where we actually test the value entered in the browser; you can substitute any string in the place of "administrator"; also you can do more sophisticated checking (e.g. replace all blanks; check for upper/lower case, etc.) if you are an experienced Java Script programmer

    To use our matchname validator create a file validation.xml and add the following lines:

          property="name"
              depends="matchname">
             
        

    Copy the files validation.xml and validator-rules.xml to the directory where your struts-config.xml resides. Let us say it is WEB-INF. Next we have to create the error message for errors.name. Create a directory WEB-INF/resources and a file in this directory with the name application.properties. Add the following lines to application.properties

    AdminForm.name=Name
    errors.name={0} should be administrator.
    errors.required={0} is required.
    errors.minlength={0} can not be less than {1} characters.
    errors.maxlength={0} can not be greater than {1} characters.
    errors.invalid={0} is invalid.
    errors.byte={0} must be a byte.
    errors.short={0} must be a short.
    errors.integer={0} must be an integer.
    errors.long={0} must be a long.
    errors.float={0} must be a float.
    errors.double={0} must be a double.
    errors.date={0} is not a date.
    errors.range={0} is not in the range {1} through {2}.
    errors.creditcard={0} is an invalid credit card number.
    errors.email={0} is an invalid e-mail address.

    Edit struts-configuration.xml and add the following lines

     
     
         path="/AdminFormValidation"
         type="test.AdminForm"
         name="AdminForm"
         scope="request"
         validate="true"
         input="admin.jsp">
         
     
     
     
    apache.struts.validator.ValidatorPlugIn">
              
                property="pathnames"
               value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>

    Create a JSP file as follows:

     
    <%@ taglib uri="struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="struts-html.tld" prefix="html" %>
     
        Administrator Test
     

    This application shows the use of Struts Validator.
    The following form contains fields that are processed by Struts Validator.
    Fill in the form and see how JavaScript generated by Validator Framework validates the form.

     

     
    Name
    Save
    Cancel
     
     

    Then we create the success.jsp

     
    <% out.println("SUCCESS") %>
     
    Then we create the Java Class for the AdminForm
    package test;
     
    import javax.servlet.http.HttpServletRequest;
     
    import org.apache.struts.action.*;
     
     
    /**
     * Form bean for the Admin Entry Screen.
     *
    */
    public class AdminForm extends ActionForm
    {
      private String name=null;
     
      public void setName(String name){
        this.name=name;
      }
     
      public String getName(){
        return this.name;
      }
     
     
        /**
         * Reset all properties to their default values.
         *
         * @param mapping The mapping used to select this instance
         * @param request The servlet request we are processing
         */
        public void reset(ActionMapping mapping, HttpServletRequest request) {
        this.name=null;
        }
     
        /**
         * Reset all properties to their default values.
         *
         * @param mapping The mapping used to select this instance
         * @param request The servlet request we are processing
       * @return errors
         */
      public ActionErrors validate(
          ActionMapping mapping, HttpServletRequest request ) {
          ActionErrors errors = new ActionErrors();
     
          if( getName() == null || getName().length() <>
            errors.add("name",new ActionMessage("error.name.required"));
          }
          }
     
          return errors;
      }
     
    }

    Create the AdminAction.java

     
    package test;
     
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
     
    public class AdminAction extends Action
    {
      public ActionForward execute(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response) throws Exception{
          return mapping.findForward("success");
      }
    }

    Finally compile the classes and restart the web server and view the AdminForm.jsp

    Developing Simple Struts Tiles Application

    Introduction
    In this section I will show you how to develop simple Struts Tiles Application. You will learn how to setup the Struts Tiles and create example page with it.

    What is Struts Tiles?
    Tiles is a framework for the development user interface. Tiles is enables the developers to develop the web applications by assembling the reusable tiles (jsp, html, etc..). Tiles uses the concept of reuse and enables the developers to define a template for the web site and then use this layout to populate the content of the web site. For example, if you have to develop a web site having more that 500 page of static content and many dynamically generated pages. The layout of the web site often changes according to the business requirement. In this case you can use the Tiles framework to design the template for the web site and use this template to populate the contents. In future if there is any requirement of site layout change then you have to change the layout in one page. This will change the layout of you whole web site.

    Steps To Create Tiles Application
    Tiles is very useful framework for the development of web applications. Here are the steps necessary for adding Tiles to your Struts application:

    1. Add the Tiles Tag Library Descriptor (TLD) file to the web.xml.
    2. Create layout JSPs.
    3. Develop the web pages using layouts.
    4. Repackage, run and test application.

    Add the Tiles TLD to web.xml file
    Tiles can can be used with or without Struts. Following entry is required in the web.xml file before you can use the tiles tags in your application.


    /tags/struts-tiles
    /WEB-INF/struts-tiles.tld


    Create layout JSPs.
    Our web application layout is divided into four parts: To Banner, Left Navigation Bar, Content Area and Bottom of the page for copy right information. Here is the code for out template (template.jsp):

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



    <b><tiles:getasstring name="title" ignore="true"></b>



















    We have defined the structure for web application using the appropriate html and did the following things:

    • Referenced the /WEB-INF/struts-tiles.tld TLD.
    • Used the string parameters to display title using the tiles:getAsString tag. If the attribute ignore="true" then Tiles ignore the missing parameter. If this is true then the Tiles framework will through the exception in case the parameter is missing.
    • To insert the content JSP, the tiles:insert tag is used, which inserts any page or web resources that framework refers to as a title. For Example inserts the header web page.

    Develop the web pages using layouts
    Now we will use tile layout create a page to display the content page in the in our application. For every content page there is additional jsp file for inserting the content in the Layout, so we have to create two jsp files one for content and another for displaying the content. In our example these file are example.jsp and content.jsp. Here is the code for both the files:

    content.jsp

    <font color="#000080" size="5">Welcome to the Title Tutorial


    This is the content page

    The content.jsp simply define the content of the page. The content may be dynamic or static depending on the requirements.

    example.jsp

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







    The code specifies the tiles layout page to be used. We have set the flush attribute to true, this makes the tile file to be written to browser before the rest of the page. To specify the title of the page is used. The following code is used to insert the actual pages in the template.:




    The top.jsp will be inserted in the layout's header region. The left.jsp will be inserted in the layout's menu region. The content.jsp wil be inserted in the layout's body region and the bottom.jsp will be inserted in the bottom region.

    Repackage, run and test application
    Add the following code in the index.jsp to test the this tile example:


  • Tiles Example


    Example of creating first tile application.
  • Use the ant tool to build the application and deploy on the server. To test the application go to the index.jps and click on the Tiles Example link.

    Using tiles-defs.xml in Tiles Application

    In the last section we studied how to forward the request (call) to a jsp page which specifies which tiles layout definition should be used to apply to the content. In this section I will show you how to use the a definition in the tiles-defs.xml for generating the content.

    In Tiles we can define the definition in the tiles-defs.xml which specifies the different components to "plugin" to generate the output. This eliminates the need to define extra jsp file for each content file. For example in the last section we defined example.jsp to display the content of content.jsp file. In this section I will show you how to eliminate the need of extra jsp file using tiles-defs.xml file.

    Steps to Use the tiles-defs.xml

    Setup the Tiles plugin in struts-config.xml file.
    Add the following code in the struts-config.xml (If not present). This enables the TilesPlugin to use the /WEB-INF/tiles-defs.xml file.






    Defining the tiles-defs.xml
    In this file we are defining the different components to "plugin". Here is the code:







    The name of the definition is Tiles.Example, we will use this in struts-config.xml (While creating forwards in struts-config.xml file) file. The page attribute defines the template file to be used and the put tag specifies the different components to "plugin". Your tiles-defs.xml should look like:



    "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
    "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">















    Configure the Struts Action to use Tiles Definition
    Open the struts-config.xml file and add the following code:

    forward="Tiles.Example"/>

    With Tiles, the action points to the Tiles definition, as shown in the above code. In this code we are using the Tiles.Example definition which we have defined in the tiles-defs.xml file. Without Tiles, forward and action definitions point directly to JSPs. With Tiles, they point to the page's definition in the Tiles configuration file.

    Testing the Application
    Create a link in index.jsp to call the Example. Code added are:


  • Using tiles-defs.xml


    Example shows you how to use tiles-defs.xml file.
  • To test the application build it using ant and deploy on the JBoss server. Type http://localhost:8080/strutstutorial/index.jsp in the bowser and select the Using tiles-defs.xml link. Your browser should show the page.

    Struts DynaActionForm

    In this tutorial you will learn how to create Struts DynaActionForm. We will recreate our address form with Struts DynaActionForm. DynaActionForm is specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean. DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. So, it makes the FormBean declarative and this helps the programmer to reduce the development time.

    In this tutorial we will recreate the add form with the help of DynaActionForm. It also shows you how you can validate use input in the action class.

    Adding DynaActionForm Entry in struts-config.xml

    First we will add the necessary entry in the struts-config.xml file. Add the following entry in the struts-config.xml file. The form bean is of org.apache.struts.action.DynaActionForm type. The tag is used to define the property for the form bean. We have defined three properties for our dynamic form bean.

    type="org.apache.struts.action.DynaActionForm">
    java.lang.String"/>


    Adding action mapping

    Add the following action mapping in the struts-config.xml file:

    name="DynaAddressForm"
    scope="request"
    validate="true"
    input="/pages/DynaAddress.jsp">




    Creating Action Class

    Code for action class is as follows:

    package roseindia.net;

    /**
    * @author Deepak Kumar
    * @Web http://www.roseindia.net
    * @Email roseindia_net@yahoo.com
    */

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.DynaActionForm;
    import org.apache.struts.action.ActionMessages;
    import org.apache.struts.action.ActionMessage;


    public class AddressDynaAction extends Action
    {
    public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{

    DynaActionForm addressForm = (DynaActionForm)form;

    //Create object of ActionMesssages
    ActionMessages errors = new ActionMessages();
    //Check and collect errors
    if(((String)addressForm.get("name")).equals("")) {
    errors.add("name",new ActionMessage("error.name.required"));
    }

    if(((String)addressForm.get("address")).equals("")) {
    errors.add("address",new ActionMessage("error.address.required"));
    }

    if(((String)addressForm.get("email")).equals("")) {
    errors.add("email",new ActionMessage("error.emailaddress.required"));
    }
    //Saves the error
    saveErrors(request,errors);
    //Forward the page
    if(errors.isEmpty()){
    return mapping.findForward("success");
    }else{
    return mapping.findForward("invalid");
    }
    }
    }

    Creating the JSP file

    We will use the Dyna Form DynaAddressForm created above in the jsp file. Here is the code of the jsp(DynaAddress.jsp) file.

    <%@ taglib uri="/tags/struts-bean" prefix="bean" %>
    <%@ taglib uri="/tags/struts-html" prefix="html" %>



    <bean:message key="welcome.title">
































    <font size="4">Please Enter the Following Details



    Name



    Address



    E-mail address



    Save

    Cancel





    Add the following line in the index.jsp to call the form.


  • Dyna Action Form Example


    Example shows you how to use DynaActionForm.
  • Building Example and Testing

    To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the DynaAddress.jsp page. Without entering anything in the form and submitting the submit button, your browser should show the following out put.

    Struts File Upload Example

    In this tutorial you will learn how to use Struts to write program to upload files. The interface org.apache.struts.upload.FormFile is the heart of the struts file upload application. This interface represents a file that has been uploaded by a client. It is the only interface or class in upload package which is typically referenced directly by a Struts application.

    Creating Form Bean

    Our form bean class contains only one property theFile, which is of type org.apache.struts.upload.FormFile. Here is the code of FormBean (StrutsUploadForm.java):

    package roseindia.net;


    import org.apache.struts.action.*;
    import org.apache.struts.upload.FormFile;



    /**
    * @author Deepak Kumar
    * @Web http://www.roseindia.net
    * @Email roseindia_net@yahoo.com
    */

    /**
    * Form bean for Struts File Upload.
    *
    */
    public class StrutsUploadForm extends ActionForm
    {
    private FormFile theFile;

    /**
    * @return Returns the theFile.
    */
    public FormFile getTheFile() {
    return theFile;
    }
    /**
    * @param theFile The FormFile to set.
    */
    public void setTheFile(FormFile theFile) {
    this.theFile = theFile;
    }
    }

    Creating Action Class

    Our action class simply calls the getTheFile() function on the FormBean object to retrieve the reference of the uploaded file. Then the reference of the FormFile is used to get the uploaded file and its information. Here is the code of our action class(StrutsUploadAction.java):

    package roseindia.net;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.upload.FormFile;
    /**
    * @author Deepak Kumar
    * @Web http://www.roseindia.net
    * @Email roseindia_net@yahoo.com
    */

    /**
    * Struts File Upload Action Form.
    *
    */
    public class StrutsUploadAction extends Action
    {
    public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    StrutsUploadForm myForm = (StrutsUploadForm)form;

    // Process the FormFile
    FormFile myFile = myForm.getTheFile();
    String contentType = myFile.getContentType();
    String fileName = myFile.getFileName();
    int fileSize = myFile.getFileSize();
    byte[] fileData = myFile.getFileData();
    System.out.println("contentType: " + contentType);
    System.out.println("File Name: " + fileName);
    System.out.println("File Size: " + fileSize);

    return mapping.findForward("success");
    }
    }

    Defining form Bean in struts-config.xml file

    Add the following entry in the struts-config.xml file for defining the form bean:

    name="FileUpload"
    type="roseindia.net.StrutsUploadForm"/>

    Defining Action Mapping

    Add the following action mapping entry in the struts-config.xml file:

    path="/FileUpload"
    type="roseindia.net.StrutsUploadAction"
    name="FileUpload"
    scope="request"
    validate="true"
    input="/pages/FileUpload.jsp">

    Developing jsp page

    Code of the jsp (FileUpload.jsp) file to upload is as follows:

    <%@ taglib uri="/tags/struts-bean" prefix="bean" %>
    <%@ taglib uri="/tags/struts-html" prefix="html" %>



    Struts File Upload Example























    <font size="4">Please Enter the Following Details



    File Name



    Upload File





    Note that we are setting the encrypt property of the form to enctype="multipart/form-data".

    code for the success page (uploadsuccess.jsp) is:




    Success




    File Successfully Received





    Add the following line in the index.jsp to call the form.


  • Struts File Upload


    Example shows you how to Upload File with Struts.
  • Building Example and Testing

    To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the FileUpload.jsp page. Your browser should display the file upload form:

    Struts File Upload and Save

    We are receiving lots of comments regarding "Struts file upload example". It does not contain any code illustrating how to save the file on the server . Now, the current example will provide you with the code to upload the file ,in the upload directory of server.

    In this tutorial you will learn how to use Struts program to upload on the Server and display a link to the user to download the uploaded file . The interface org.apache.struts.upload.FormFile has a prime role in uploading a file in a Struts application. This interface represents a file that has been uploaded by a client. It is the only interface or class in Upload package which is referenced directly by a Struts application.

    Creating Form Bean

    Our form bean class contains only one property theFile, which is of type org.apache.struts.upload.FormFile. Here is the code of FormBean (StrutsUploadAndSaveForm.java):

    package roseindia.net;


    import org.apache.struts.action.*;
    import org.apache.struts.upload.FormFile;



    /**
    * @author Amit Gupta
    * @Web http://www.roseindia.net
    * @Email struts@roseindia.net
    */

    /**
    * Form bean for Struts File Upload.
    *
    */
    public class StrutsUploadAndSaveForm extends ActionForm
    {
    private FormFile theFile;

    /**
    * @return Returns the theFile.
    */
    public FormFile getTheFile() {
    return theFile;
    }
    /**
    * @param theFile The FormFile to set.
    */
    public void setTheFile(FormFile theFile) {
    this.theFile = theFile;
    }
    }

    Creating Action Class

    In our previous article entitled "Struts File Upload Example", we just had action class simply calling the getTheFile() function on the FormBean object to retrieve the reference of the uploaded file. Then the reference of the FormFile was used to get the uploaded file and its information. Now further we retrieve the Servers upload directory's real path using ServletContext's getRealPath() and saving the file.

    Code of StrutsUploadAndSaveAction.java:

    package roseindia.net;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.upload.FormFile;
    import java.io.*;

    /**
    * @author Amit Gupta
    * @Web http://www.roseindia.net
    * @Email struts@roseindia.net
    */

    /**
    * Struts File Upload Action Form.
    *
    */
    public class StrutsUploadAndSaveAction extends Action
    {
    public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    StrutsUploadAndSaveForm myForm = (StrutsUploadAndSaveForm)form;

    // Process the FormFile
    FormFile myFile = myForm.getTheFile();
    String contentType = myFile.getContentType();
    //Get the file name
    String fileName = myFile.getFileName();
    //int fileSize = myFile.getFileSize();
    byte[] fileData = myFile.getFileData();
    //Get the servers upload directory real path name
    String filePath = getServlet().getServletContext().getRealPath("/") +"upload";
    /* Save file on the server */
    if(!fileName.equals("")){
    System.out.println("Server path:" +filePath);
    //Create file
    File fileToCreate = new File(filePath, fileName);
    //If file does not exists create file
    if(!fileToCreate.exists()){
    FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
    fileOutStream.write(myFile.getFileData());
    fileOutStream.flush();
    fileOutStream.close();
    }


    }
    //Set file name to the request object
    request.setAttribute("fileName",fileName);

    return mapping.findForward("success");
    }
    }

    Defining form Bean in struts-config.xml file

    Add the following entry in the struts-config.xml file for defining the form bean:

    name="FileUploadAndSave"
    type="roseindia.net.StrutsUploadAndSaveForm"/>

    Defining Action Mapping

    Add the following action mapping entry in the struts-config.xml file:

    path="/FileUploadAndSave"
    type="roseindia.net.StrutsUploadAndSaveAction"
    name="FileUploadAndSave"
    scope="request"
    validate="true"
    input="/pages/FileUploadAndSave.jsp">

    Developing jsp pages

    Code of the jsp (FileUploadAndSave.jsp) file to upload is as follows

    <%@ taglib uri="/tags/struts-bean" prefix="bean" %>
    <%@ taglib uri="/tags/struts-html" prefix="html" %>



    Struts File Upload and Save Example






















    File Upload on Server



    File Name



    Upload File





    code for the success page (downloaduploadedfile.jsp) is:




    Success



    <%
    String fileName=(String)request.getAttribute("fileName");
    %>

    File Successfully Received


    ">Click here to download




    Add the following line in the index.jsp to call the form.


  • Struts File Upload


    Example shows you how to Upload File with Struts.
  • Building Example and Testing

    To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the Struts File Upload page. Your browser should display the file upload form:

    Now , Browse the file needed to upload and click Upload File Button. Browser will display that file has successfully received on the server.

    Click on the hyperlink to see the uploaded content. .

    Struts Built-In Actions

    In this section we will give a quick look to the few of built-in utility actions shipped with Struts APIs. These built-in utility actions provide different functionalities useful to diverse applications.

    Actions

    Description

    org.apache.struts.actions.DispatchAction

    It provides mechanism to collect related functions into a single action and eliminates the need of creating multiple independent actions for each function.

    org.apache.struts.actions.ForwardAction

    It enables to forward request to the specified URL.

    org.apache.struts.actions.IncludeAction

    It provides mechanism to include the contents of a specified URL.

    org.apache.struts.actions.LocaleAction

    It provides mechanism to set a user's locale and further forwarding that to a specified page.

    org.apache.struts.actions.LookupDispatchAction

    It provides mechanism to combine many similar actions into a single action class, in order to simplify the application design .Java map class is used to dispatch methods.

    org.apache.struts.actions.MappingDispatchAction

    It lets you combine many related actions into a single action class and manage through creating multiple action-mappings.

    org.apache.struts.actions.switchAction

    It provides a mechanism to switch between modules and then forwards control to a URI (specified in a number of possible ways) within the new module.

    Struts Dispatch Action Example

    Struts Dispatch Action (org.apache.struts.actions.DispatchAction) is one of the Built-in Actions provided along with the struts framework.

    The org.apache.struts.actions.DispatchAction class enables a user to collect related functions into a single Action. It eliminates the need of
    creating multiple independent actions for each function. Here in this example you will learn more about Struts Dispatch Action that will help you grasping the concept better.

    Let's develop Dispatch_Action class which is a sub class of org.apache.struts.actions.DispatchAction class. This class does not provide an implementation for the execute() method because DispatchAction class itself implements this method. This class manages to delegate the request to one of the methods of the derived Action class. An Action Mapping is done to select the particular method (via Struts-Configuration file).

    Here the Dispatch_Action class contains multiple methods ie.. add() , edit() , search() , save(). Here all the methods are taking the same input parameters but each method returns a different ActionForward like "add" in case of add() method , "edit" in case of edit() etc.
    Each ActionForward is defined in the struts-config.xml file (action mapping is shown later in this page). Here is the code for Action Class.

    Developing an Action Class (Dispatch_Action.java)

    package roseindia.net;

    import java.io.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletException;
    import org.apache.struts.actions.DispatchAction;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;

    /**
    * @author Amit Gupta
    * @Web http://www.roseindia.net
    * @Email struts@roseindia.net

    **/

    public class Dispatch_Action extends DispatchAction

    {

    public ActionForward add(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    System.out.println("You are in add function.");
    return mapping.findForward("add");
    }

    public ActionForward edit(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception

    {


    System.out.println("You are in edit function.");
    return mapping.findForward("edit");

    }

    public ActionForward search(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    System.out.println("You are in search function");
    return mapping.findForward("search");

    }

    public ActionForward save(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    System.out.println("You are in save function");
    return mapping.findForward("save");

    }

    }

    Developing an ActionForm Class

    Our form bean class contains only one property "parameter" which is playing prime role in this example. Based on the parameter value appropriate function of Action class is executed. Here is the code for FormBean ( DispatchActionForm.java):

    package roseindia.net;

    import org.apache.struts.action.ActionForm;

    /**

    * @author Amit Gupta
    * @Web http://www.roseindia.net
    * @Email struts@roseindia.net

    **/

    public class DispatchActionForm extends ActionForm
    {

    private String parameter =" ";
    public String getParameter()

    {

    return parameter;

    }


    public void setParameter(String parameter)

    {

    this.parameter=parameter;

    }

    }



    Defining form Bean in struts-config.xml file

    Add the following entry in the struts-config.xml file for defining the form bean

    type="roseindia.net.DispatchActionForm"/>


    Developing the Action Mapping in the struts-config.xml

    Here, Action mapping helps to select the method from the Action class for specific requests. Note that the value specified with the parameter
    attribute is used to delegate request to the required method of the Dispath_Action Class.

    path="/DispatchAction"
    type="roseindia.net.Dispatch_Action"
    parameter="parameter"
    input="/pages/DispatchAction.jsp"
    name="DispatchActionForm"
    scope="request"
    validate="false">




    Developing jsp page

    Code of the jsp (DispatchAction.jsp) to delegate requests to different jsp pages :

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


    Dispatch Action Example


    Dispatch Action Example


    Call Add Section


    Call Edit Section


    Call Search Section


    Call Save Section



    Add the following line in the index.jsp to call the form.


  • Struts File Upload


    Example demonstrates how DispatchAction Class works.
  • Building and Testing the Example

    To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the DispatchAction.jsp page. Your browser displays the following DispatchAction page.

    Selecting Call Add Section displays the following DispatchActionAdd.jsp page

    Selecting Call Edit Section displays the following DispatchActionEdit.jsp page

    Selecting Call Search Section displays the following DispatchActionSearch.jsp page

    Selecting Call Save Section displays the following DispatchActionSave.jsp page

    Struts Forward Action Example

    In this section we will learn about Struts ForwardAction (org.apache.struts.actions.ForwardAction). The ForwardAction is one of the Built-in Actions that is shipped with struts framework.

    The org.apache.struts.actions.ForwardAction class enables a user to forward request to the specified URL. ForwardAction is an utility classs that is used in cases where a user simply needs to forward the control to an another JSP page. Linking directly a JSP to an another, violates the MVC principles. So we achieve this through action-mapping. Note that we do not create any action class. With ForwardAction , simply create an action mapping in the Strut Configuration and specify the location where the action will forward the request..

    Here in this example you will learn more about Struts Forward Action that will help you in grasping the concept better.

    No need to develop an Action Class

    Developing the Action Mapping in the struts-config.xml

    Create seperate action-mapping , for each page you want to link.. Note that the "type" attribute always take "org.apache.struts.actions.ForwardAction" value. Here "parameter" attribute specifies the URL to which the request is forwarded .

    path="/success"
    type="org.apache.struts.actions.ForwardAction"
    parameter="/pages/Success.jsp"

    input="/pages/ForwardAction.jsp"
    scope="request"
    validate="false">

    Developing a jsp page

    Code of the jsp (ForwardAction.jsp) to forward request to a different jsp page :


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


    Forward Action Example


    Forward Action Example


    Call the Success page


    Add the following line in the index.jsp to call the form.


  • Struts Forward Action


    Example shows you how to use forward class to forward request to another JSP page.
  • Building and Testing the Example

    To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the ForwardAction.jsp page. Your browser will display the following ForwardAction page.

    Selecting Call the Success page displays the following Success.jsp page

    Struts LookupDispatchAction Example

    Struts LookupDispatch Action (org.apache.struts.actions.LookupDispatchAction) is one of the Built-in Actions provided along with the struts framework.

    .The org.apache.struts.actions.LookupDispatchAction class.is a subclass of org.apache.struts.actions.DispatchAction class.This class enables a user to collect related functions into a single action class. It eliminates the need of creating multiple independent actions for each function. Here in this example you will learn more about Struts LookupDispatchAction that will help you to grasp the concept better.

    Let's develop a class LookupDispatch_Action which is a sub class of org.apache.struts.actions.LookupDispatchAction class. This class does not provide an implementation for the execute() method because DispatchAction class itself implements this method. LookupDispatchAction class is much like the DispatchAction class except that it uses a Java Map and ApplicationResource.properties file to dispatch methods . At run time, this class manages to delegate the request to one of the methods of the derived Action class. Selection of a method depends on the value of the parameter passed from the incoming request. LookupDispatchAction uses this parameter value to reverse-map to a property in the Struts Resource bundle file (ie..ApplicationResource.properties). This eliminates the need of creating an instance of ActionForm class.

    LookupDispatch_Action class contains multiple methods ie.. add() , edit() , search() , save() . Here all the methods are taking the same input parameters but each method returns a different ActionForward like "add" in case of add() method , "edit" in case of edit() etc. Each ActionForward is defined in the struts-config.xml file (action mapping is shown later in this page).

    Notice the implementation of the getKeyMethodMap()method.This method is required to map the names of the keys in the Struts Resource bundle file (ie..ApplicationResource.properties) to the methods in the class. The key values in the bundle file are matched against the value of the incoming request parameter ( which is specified in the action tag through struts-config.xml file). Then this matching key is mapped to the appropriate method to execute ,the mecahanism is implemented through the getKeyMethodMap()and can be defined as key-to-method mapping.

    Here is the code for Action Class

    Developing an Action Class (LookupDispatch_Action.java)

    package roseindia.net;

    /**
    * @author Amit Gupta
    * @Web http://www.roseindia.net
    * @Email struts@roseindia.net
    **/

    import java.io.*;
    import java.util.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletException;
    import org.apache.struts.actions.LookupDispatchAction;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;

    public class LookupDispatch_Action extends LookupDispatchAction
    {
    protected Map getKeyMethodMap(){
    Map map = new HashMap();
    map.put("roseindia.net.add","add");
    map.put("roseindia.net.edit","edit");
    map.put("roseindia.net.search","search");
    map.put("roseindia.net.save","save");
    return map;
    }


    public ActionForward add(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    System.out.println("You are in add function.");
    return mapping.findForward("add");
    }

    public ActionForward edit(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    System.out.println("You are in edit function.");
    return mapping.findForward("edit");
    }

    public ActionForward search(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    System.out.println("You are in search function");
    return mapping.findForward("search");
    }

    public ActionForward save(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    System.out.println("You are in save function");
    return mapping.findForward("save");
    }
    }

    No need to Develop an ActionForm Class

    Instead create an Application Resource Property File:

    Application.properties
    in the same directory structure where classes are saved.

    roseindia.net.add=add
    roseindia.net.edit=edit
    roseindia.net.search=search
    roseindia.net.save=save

    Add the following, Message Resources Definitions in struts-config.xml

    Develop the following Action Mapping in the struts-config.xml

    Here, Action mapping helps to select the method from the Action class for specific requests. Note that the value specified with the parameter
    attribute is used to delegate request to the required method of the LookupDispatch_Action Class.

    path="/LookupDispatchAction"
    type="roseindia.net.LookupDispatch_Action"
    parameter="parameter"
    input="/pages/LookupDispatchAction.jsp"
    name="LookupDispatchActionForm"
    scope="request"
    validate="false">




    Developing jsp page

    Code of the jsp (LookupDispatchAction.jsp) to delegate requests to different jsp pages :

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


    Dispatch Action Example


    Dispatch Action Example


    Call Add Section


    Call Edit Section


    Call Search Section


    Call Save Section



    Add the following line in the index.jsp to call the form.


  • Struts File Upload


    Example demonstrates how LookupDispatchAction class works.
  • Building and Testing the Example

    To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the LookupDispatchAction.jsp page. Your browser displays the following LookupDispatchAction page.

    Selecting Call Add Section displays the following LookupDispatchActionAdd.jsp page

    Selecting Call Edit Section displays the following LookupDispatchActionEdit.jsp page

    Selecting Call Search Section displays the following LookupDispatchActionSearch.jsp page

    Selecting Call Save Section displays the following LookupDispatchActionSave.jsp page

    STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS


    If you are a Struts developer then you might have experienced the pain of writing huge number of Action classes for your project. The latest version of struts provides classes using which you can aggregate a related set of actions into a single unified action. In this article we will see how to achieve this. Struts provides four important classes for this purpose. These classes are called as Dispatchers. The important Dispatchers that struts provides includes : DispatchAction, ActionDispatcher , LookupDispatchAction and MappingDispatchAction.

    All these classes can be found in the package org.apache.struts.actions. Let us look in to each of these in detail. Our examples use the simple CRUD actions.

    DispatchAction: In this type of aggregation, the action class must extend DispatchAction class as shown.

    public final class CRUDDispatchAction extends DispatchAction {

    public ActionForward create(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception {
    return (mapping.findForward("success"));
    }
    ...

    and the action mapping will be as





    in your jsp you can call this action as

    Create
    ...

    Observe that the above class extends DispatchAction and so you cannot use this method if your class already extends your (some) super class (eg., the class where the session is validated/invalidated). Here the user has to send a query string variable (methodToCall) to set the action name to call.

    ActionDispatcher: This flavor of aggregation is same as DispatchAction except that we need not extend ActionDispatcher, so we can use this method even if our class extends a super class. The following code snippet shows this scenario.


    public final class CRUDActionDispatcher extends Action {

    protected ActionDispatcher dispatcher = new ActionDispatcher(this, ActionDispatcher.DEFAULT_FLAVOR);

    public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception {
    return dispatcher.execute(mapping, form, request, response);
    }

    The DEFAULT_FLAVOR field suggests that the default parameter is "method" if none is specified as parameter in struts-config.xml (eg,. methodToCall).
    ActionDispatcher flavor also needs methodToCall parameter to be set (using hidden variable or a query string) as in case of DispatchAction.

    LookupDispatchAction: This type of aggregation is useful in situations where in you have multiple submit buttons in a single form. The class must extend LookupDispatchAction. However, the great thing about this type is that its java script free. That means, you need not set any hidden variables or pass query string however, you must use submit buttons as shown.



    ...
    The example Action class will be as follows

    public class CRUDLookUpDispatchAction extends LookupDispatchAction {

    protected Map getKeyMethodMap() {
    Map map = new HashMap();
    map.put("button.create", "create");

    return map;
    }
    public ActionForward create(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception {
    return (mapping.findForward("success"));
    }
    Observe the getKeyMethodMap() method. The submit button names are specified in a Map and their keys comes from MessageResources file. Struts picks up the name from this file and redirects it to the value specified in the Map. The calling code in jsp however has multiple submit buttons only differing in their names.

    MappingDispatchAction: This aggregation extends MappingDispatchAction class. This is the most useful type among the four types available. But as seen in other cases, you can use this type only when your action does not extend any other action. The good thing about this type is that the action mappings can differ and so need not be the same as in all other cases. To illustrate this consider the below mappings.








    Notice that in the first action mapping, there is no form bean while in the second the bean name is specified. This means that the user has the flexibility to change the mapping according to his needs and hence not been contained to use a constant mapping for all the CRUD actions. Note that in all the other types of aggregations, we must use the same mapping for all the CRUD actions.

    Conclusion: Each of these types has their own pros and cons. DispatchAction is the default type which uses java script and we must extend DispatchAction to use it, ActionDispatcher is same as DispathAction except that we do not extend any action , LookupDispatchAction gives the flexibility to use multiple submit buttons while MappingDispatchAction allows us to change the action mappings according to our need. So each one of these has a particular usage and which one to use depends on the user requirement.

    Set the mapping name

    3. Set the mapping name to the action attribute of html:link





























    // mappingdispatchaction.jsp



    Create an Employee record



    Read an Employee details



    Update Employee details



    Delete Employee record

    What are the advantages?

    1. Single action class can be used for multiple action mappings. The attribute of the action mapping can be added or removed and a new mapping can be created while the action class remains the same.
    2. Useful in places where there are 2 actions, one of which needs a formbean while the other does not but both uses the same Action class. In such cases, two new action mappings can be created one with ‘name' attribute and one without and the same Action class name can be used.

    What are the disadvantages?

    1. We still cannot extend our CRUDMappingDispatchAction from any custom base class and have the aggregation intact.
    2. Cannot attach events. More about this later.

    ActionDispatcher

    How to create one?

    1. Extend your action class from Action. Do not confuse about the inclusion of BaseAction.java. I have just moved the common code part to this BaseAction and extended my action class from it.

    // src/CRUDActionDispatcher.java

    /**

    * This is an example class for demonstrating ActionDispatcher

    * functionality. Observe here that we are extending our

    * action class from BaseAction where the session validation

    * is done.

    *



    * See BaseAction for more details

    *



    * If we use any other aggregating action then we cannot

    * use session validation as we cannot extend our custom class

    * (BaseAction in this case). This is the biggest strength of ActionDispatcher

    * type of aggregation and the biggest weakness of all other types.

    *

    * @author Praveen Babu Kusuma

    * @version 1.0.0

    *

    * http://www.javahome.co.nr

    * http://praveen.awardspace.com

    */

    public final class CRUDActionDispatcher extends BaseAction {

    public ActionForward create(ActionMapping mapping,

    ActionForm form,

    HttpServletRequest request,

    HttpServletResponse response)

    throws Exception {

    // Code for Create Employee follows

    System.out.println("I am in CRUDActionDispatcher - create");

    return ( mapping.findForward("success") );

    }

    ...

    }

    // src/BaseAction.java

    /**

    * This is an example class where session validation

    * is done normally. But if you look at closely we have

    * actually written our ActionDispatcher code here and

    * simply extended our example class for demonstrating

    * ActionDispatcher functionality from this class.

    *



    * This is the place where every time the session is

    * checked. A sample code snippet could be :

    *

    *

    * session = request.getSession(false); // which returns the existing session

    * if( session != null ) {

    * // allow the user in

    * } else {

    * // throw him/her out to the relogin page

    * }

    *


    *



    * This is perhaps the most crucial part of any web application

    * since this is to be done for every class or every class is to be

    * extended from this kind of (Base) class.

    *

    * @author Praveen Babu Kusuma

    * @version 1.0.0

    *

    * http://www.javahome.co.nr

    * http://praveen.awardspace.com

    */

    public class BaseAction extends Action {

    protected ActionDispatcher dispatcher =

    new ActionDispatcher(this, ActionDispatcher.DEFAULT_FLAVOR);

    public ActionForward execute(ActionMapping mapping,

    ActionForm form,

    HttpServletRequest request,

    HttpServletResponse response)

    throws Exception {

    // This is a default method and is mandatory since we are

    // not extending any dispatcher action class(eg, extends ActionDispatcher{ }).

    // This method will handle the dispatching of the action to the appropriate method.

    // Code for Session Validation follows

    System.out.println("I am in BaseAction - execute");

    return dispatcher.execute(mapping, form, request, response);

    }

    }

    2. Declare a variable of type ActionDispatcher as follow (see above code snippet):

    protected ActionDispatcher dispatcher = new ActionDispatcher(this, ActionDispatcher.DEFAULT_FLAVOR);

    3. Add the following line as the last line of your default ‘execute' method. Note that this is not needed for other methods. (see above code snippet)

    return dispatcher.execute(mapping, form, request, response);

    4. Define a query string parameter or a hidden variable (‘methodToCall' in our examples)





    // actiondispatcher.jsp



    Create an Employee record

    5. Set the parameter's value to the desired function name of the action class (create, read etc).






    // actiondispatcher.jsp





    // actiondispatcher.jsp



    Create an Employee record



    Create an Employee record

    What are the advantages?

    1. Observe that we have extended our action class (CRUDActionDispatcher) from our custom base class (BaseClass) which is what we wanted in order to decouple the session validation code into the BaseClass.
    2. Only a couple of changes to the code avoid the need to extend from a subclass.
    3. Easy to use.

    What are the disadvantages?

    1. We cannot attach events to the controls.

    Event Aggregating Actions

    If you are familiar with swing programming you might have heard of events. An event is nothing but a piece of code that is executed when, say, a button is clicked, a linked is clicked etc. In all the above types of actions we have defined a parameter (methodToCall) which is in turn mapped to the action name. This is a good feature for security concerns. However, we need a way to have the method name different from the actual method called, at the same time eliminating the need to define a hidden variable or a query string. This is where the Event Aggregating Actions comes into the picture.

    There are two important types of Event Aggregating Actions as said earlier, namely, EventDispatchAction and EventActionDispatcher

    Let's see each one of them in detail.

    EventDispatchAction

    How to create one?

    1. Extend your action from EventDispatchAction

    // CRUDEventDispatchAction.java

    /**

    * This is an example class for demonstrating EventDispatchAction

    * functionality. Observe here that we can also extend our class from

    * BaseAction class like in ActionDispatcher example and move our

    * session validation to that class.

    *



    * The EventActionDispatcher as the name suggests is used to attach

    * events to the html controls. This type of aggregation eliminates the

    * need to define a parameter(eg., methodToCall). We havent used any

    * hidden parameters to combine an event to a method. This event-to-method

    * mapping is removed using EventActionDispatcher.

    *

    * We can also use an Alias for the method name and map it to the method name

    * as can be seen in the createAlias event.

    *

    * @author Praveen Babu Kusuma

    * @version 1.0.0

    *

    * http://www.javahome.co.nr

    * http://praveen.awardspace.com

    */

    public final class CRUDEventDispatchAction extends EventDispatchAction {

    public ActionForward create(ActionMapping mapping,

    ActionForm form,

    HttpServletRequest request,

    HttpServletResponse response) throws Exception {

    // Code for Create Employee follows

    System.out.println("I am in CRUDEventDispatchAction - create");

    return ( mapping.findForward("success") );

    }

    ...

    }

    Set the action name

    2. Set the action name to the action attribute of html:link

    // eventdispatchaction.jsp

    Create an Employee record

    3. Either directly use the method name to call as a query string parameter, or use an alias.





    // eventdispatchaction.jsp ( Direct calling )



    Update Employee details





    // eventdispatchaction.jsp ( Calling using an alias )



    Create an Employee record

    What are the advantages?

    1. Events can be attached to controls directly.

    2. No need to use a separate hidden variable or a query string for mapping the method name to the actual method to call.

    3. Actual method to call can be aliased with a pseudo name.

    What are the disadvantages?

    1. The need to extend the class from EventDispatchAction and hence cannot extend our class from a custom base class.

    EventActionDispatcher

    How to create one?

    1. Extend your action from Action, similar to the case in ActionDispatcher. This is what is desirable for us.

    // CRUDEventActionDispatcher.java

    /**

    * This is an example class for demonstrating EventActionDispatcher

    * functionality. Observe here that we can also extend our class from

    * BaseAction class like in ActionDispatcher example and move our

    * session validation to that class.

    *



    * The EventActionDispatcher as the name suggests is used to attach

    * events to the html controls. This type of aggregation eliminates the

    * need to define a parameter(eg., methodToCall). We havent used any

    * hidden parameters to combine an event to a method. This event-to-method

    * mapping is removed using EventActionDispatcher.

    *

    * We can also use an Alias for the method name and map it to the method name

    * as can be seen in the createAlias event.

    *

    * @author Praveen Babu Kusuma

    * @version 1.0.0

    *

    * http://www.javahome.co.nr

    * http://praveen.awardspace.com

    */

    public final class CRUDEventActionDispatcher extends Action {

    protected ActionDispatcher dispatcher = new EventActionDispatcher(this);

    public ActionForward execute(ActionMapping mapping,

    ActionForm form,

    HttpServletRequest request,

    HttpServletResponse response) throws Exception {

    // This method will handle the dispatching of the action to the appropriate method.

    System.out.println("I am in CRUDEventActionDispatcher - execute");

    return dispatcher.execute(mapping, form, request, response);

    }

    ...

    }

    2. Set the action name to the action attribute of html:link.





    // eventactiondispatcher.jsp



    Create an Employee record

    3. Either directly use the method name to call as a query string parameter, or use an alias.





    // eventactiondispatcher.jsp ( Direct calling )



    Delete Employee record





    // eventactiondispatcher.jsp ( Calling using an alias )



    Create an Employee record

    What are the advantages?

    1. Events can be attached to controls directly.

    2. No need to use a separate hidden variable or a query string for mapping the method name to the actual method to call.

    3. Actual method to call can be aliased with a pseudo name.

    What are the disadvantages?

    1. None.

    Note that the use of true (read=true) while using the query string variable to specify the event name is optional. Also, note that this variable is different from the one we used earlier (methodToCall). Here we directly specify the event name or its alias not the variable name or the actual method to call.

    Assumptions

    1. It is assumed that you have the complete source code of this discussion with you.

    2. For some examples, I assume that our application is a full fledged web application wherein a user is authenticated before entry into the system and we are validating the user session in a base class. Why is this so important? Because, to use some types of aggregations, we should extend our action class from a specific subclass of Action. This restricts us from extending the action class from a custom base class. DispatchAction is an example of such an action.

    3. It is assumed that all we are interested in are the Create, Read, Update and Delete operations on an entity in the database. These
    actions, also called CRUD actions, are the basis for all the examples of this discussion.

    4. One more assumption is that it is assumed that we are interested in attaching events to the HTML controls, which you may be familiar in JSF, where in we attach events to the controls using action and actionListener attributes.

    5. It is assumed that the examples provided depict only one way of usage. You are free to experiment with the code, like for instance, replacing query string with hidden variables.

    Configuring Struts DataSource Manager on Tomcat 5

    This tutorial shows you how you can configure Struts DataSource Manager on the Tomcat 5.5.9 server. We will use struts 1.2.7 in this tutorial. In this tutorial we will configure Struts DataSource Manager to use MySQL Database and use the connection provided by Struts DataSource in action class.

    Downloading and Installing Tomcat 5.5.9
    Download jakarta-tomcat-5.5.9 from http://jakarta.apache.org/tomcat/. Install it on your machine. Run and test the pages that comes with the tomcat.

    Download Struts
    Download Struts struts-1.2.7 from http://struts.apache.org/download.cgi and unzip it to your favorite directory. Go to the struts-1.2.7\webapps directory and then unzip struts-blank.war file. We will use this file to write our tutorial.

    Download MySQL JDBC Driver
    Download mysql-connector-java-3.0.16-ga-bin.jar from here mysql-connector-java-3.0.16-ga-bin.jar or you can download and use the latest version of mysql jdbc driver. Copy the JDBC driver file (mysql-connector-java-3.0.16-ga-bin.jar or latest version) to the jakarta-tomcat-5.5.9\common\lib directory of your tomcat installation. This will add the MySQL JDBC driver to the tomcat server.

    Creating MySQL Database
    In this tutorial I am using MySQL server installed on my local machine. You can download and install MySQL on your local machine and use for this tutorial. If you already have MySQL server then you can use the existing MySQL server.

    Create database "strutsdatabase" on the MySQL server and then run the following query to create test table.

    CREATE TABLE `test` (
    `username` varchar(20) NOT NULL default ''
    ) TYPE=MyISAM;

    /*Data for the table `test` */

    insert into `test` values ('rajesh'),('George'),('Vikas'),('Prakash'),('Mahesh');

    Above query creates test table and then populates the table with data.

    Configuring Struts Application
    Now create a directory "strutsdatabase" in the jakarta-tomcat-5.5.9\webapps\ directory and copy the content of struts-blank application (unzipped above) in the strutsdatabase directory.

    Now start the tomcat and try to access the strutsdatabase application by typing the url http://localhost:8080/strutsdatabase in browser. Your browser should display the welcome page. After testing shutdown the tomcat server.

    Configuring Struts DataSource Manager
    The Struts DataSource manager makes it easy for your Action class get the database connection. To configure the Stuts DataSource Manager we will uncomment the entry in the struts-config.xml.

    Uncomment and then entry in the struts-config.xml and then change the line "org.apache.commons.dbcp.BasicDataSource" to "org.apache.tomcat.dbcp.dbcp.BasicDataSource". In tomcat 5.5.9 dbcp classes are packaged in naming-factory-dbcp.jar archieve, so we are using "org.apache.tomcat.dbcp.dbcp.BasicDataSource" instead of "org.apache.commons.dbcp.BasicDataSource". After this change the database dirver, database url and passwor in the tag.

    You <data-source> element should look like:

    org.apache.tomcat.dbcp.dbcp.BasicDataSource">
        
          property="driverClassName"
          value="com.mysql.jdbc.Driver" />
        
          property="url"
          value="jdbc:mysql://localhost:3306/strutsdatabase?autoReconnect=true" />
        
          property="username"
          value="root" />
        
          property="password"
          value="" />
        
          property="maxActive"
          value="10" />
        
          property="maxWait"
          value="5000" />
        
          property="defaultAutoCommit"
          value="false" />
        
          property="defaultReadOnly"
          value="false" />
        
          property="validationQuery"
          value="SELECT COUNT(*) FROM test" />
            

    Create action Class to Test the DataSource
    Now we will write the code of Action class for getting the connection form DataSource:

    package test;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;

    import java.sql.*;

    public class TestDataSource extends Action
    {
    public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{

    javax.sql.DataSource dataSource;
    java.sql.Connection myConnection=null;
    try {
    dataSource = getDataSource(request);
    myConnection = dataSource.getConnection();
    Statement stmt=myConnection.createStatement();
    ResultSet rst=stmt.executeQuery("select username from test");
    System.out.println("******************************************");
    System.out.println("********Out Put from TestDataSource ******");
    while(rst.next()){
    System.out.println("User Name is: " + rst.getString("username"));
    }
    System.out.println("******************************************");
    rst.close();
    stmt.close();
    // do what you wish with myConnection
    } catch (SQLException sqle) {
    getServlet().log("Connection.process", sqle);
    } finally {
    //enclose this in a finally block to make
    //sure the connection is closed
    try {
    myConnection.close();
    } catch (SQLException e) {
    getServlet().log("Connection.close", e);
    }
    }


    return mapping.findForward("success");
    }
    }

    Following code is used to get the data source and then connection from Struts DataSource:

    dataSource = getDataSource(request);
    myConnection = dataSource.getConnection();

    Save this file(TestDataSource.java) into jakarta-tomcat-5.5.9\webapps\strutsdatabase\WEB-INF\src\java\test directory. Add the servlet API into class path. Then open dos prompt and navigate to jakarta-tomcat-5.5.9\webapps\strutsdatabase\WEB-INF\src\ directory and issue run ant. This will compile the action class (TestDataSource.java) and copy it to the classes directory of the webapplication.

    Creating Action Mapping struts-config.xml
    Now add the following action mapping into the struts-config.xml:

    path="/DataSource"
    type="test.TestDataSource">

    Running and testing
    Start tomcat and browse the url http://localhost:8080/strutsdatabase/DataSource.do. Your browser should show the following output.

    Now check tomcat console, it should display records fetched from database.

    You can download my struts-config.xml from here.

    Note: The DataSource manager is being retained in Struts 1.x for backward compatibility but may not be retained in Struts 2.x or later.

    0 comments:

    Search

    My Blog List