Struts Guide

52
Struts Guide 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 logics 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.

description

Struts Guide

Transcript of Struts Guide

Struts Guide

Struts Guide

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 logics 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 goes 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.

Developing First Struts Application

Rename struts-blank.war to struts-tutorial.war from jakarta-tomcat-5.0.4\webapps and copy it to the "jakarta-tomcat-5.0.4\webapps" directory. Tomcat automatically extracts the file and loads the application.

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

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.

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

First Request to the controller

Once the use clicks 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?

The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need toSubclass and overwrite the execute () method. In the Action Class all the database/business processing is done. It is advisable to perform all the database related stuffs in the Action Class.

The ActionServlet (command) 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 a 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

packageroseindia.net;

importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;

importorg.apache.struts.action.Action;importorg.apache.struts.action.ActionForm;importorg.apache.struts.action.ActionForward;importorg.apache.struts.action.ActionMapping;

publicclassTestActionextendsAction{publicActionForwardexecute(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{returnmapping.findForward("testAction");}}

Understanding Action ClassHere is the signature of the Action Class.public ActionForward execute(ActionMappingmapping,

ActionFormform,

javax.servlet.http.HttpServletRequestrequest,

javax.servlet.http.HttpServletResponseresponse)

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.xmlTo test the application we will add a link in the index.jspTest the Action

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

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 that extends the ActionForm class. Here is the code of the class:AddressForm.java

packageroseindia.net;

importjavax.servlet.http.HttpServletRequest;

importorg.apache.struts.action.*;

/***FormbeanfortheAddressEntryScreen.**/publicclassAddressFormextendsActionForm{privateStringname=null;privateStringaddress=null;privateStringemailAddress=null;

publicvoidsetName(Stringname){this.name=name;}

publicStringgetName(){returnthis.name;}

publicvoidsetAddress(Stringaddress){this.address=address;}

publicStringgetAddress(){returnthis.address;}

publicvoidsetEmailAddress(StringemailAddress){this.emailAddress=emailAddress;}

publicStringgetEmailAddress(){returnthis.emailAddress;}

/***Resetallpropertiestotheirdefaultvalues.**@parammappingThemappingusedtoselectthisinstance*@paramrequestTheservletrequestweareprocessing*/publicvoidreset(ActionMappingmapping,HttpServletRequestrequest){this.name=null;this.address=null;this.emailAddress=null;}

/***Resetallpropertiestotheirdefaultvalues.*@parammappingThemappingusedtoselectthisinstance*@paramrequestTheservletrequestweareprocessing*@returnerror*/

publicActionErrorsvalidate(ActionMappingmapping,HttpServletRequestrequest){ActionErrorserrors=newActionErrors();if(getName()==null||getName().length()

Creating Message ResourcesMessage 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=NameAddressForm.address=AddressAddressForm.emailAddress=E-mail address

Developing Validation rulesIn 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.

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 tag. The value of key is taken from the message resources (Struts\strutstutorial\web\WEB-INF\MessageResources.properties).

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

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.

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.

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

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.

Developing Simple Struts Tiles Application

IntroductionIn 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 ApplicationTiles is very useful framework for the development of web applications. Here are the steps necessary for adding Tiles to your Struts application:

Add the Tiles Tag Library Descriptor (TLD) file to the web.xml.

Create layout JSPs.

Develop the web pages using layouts.

Repackage, run and test application.

Add the Tiles TLD to web.xml fileTiles 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):

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 layoutsNow 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

Welcome to the Title TutorialThis 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

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 applicationAdd 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.xmlIn 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:

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

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 ApplicationCreate 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.

Adding action mapping

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

Creating Action Class

Code for action class is as follows:

packageroseindia.net;

/***@authorDeepakKumar*@Webhttp://www.roseindia.net*@[email protected]*/

importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;

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

publicclassAddressDynaActionextendsAction{publicActionForwardexecute(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{

DynaActionFormaddressForm=(DynaActionForm)form;

//CreateobjectofActionMesssagesActionMessageserrors=newActionMessages();//Checkandcollecterrorsif(((String)addressForm.get("name")).equals("")){errors.add("name",newActionMessage("error.name.required"));}

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

if(((String)addressForm.get("email")).equals("")){errors.add("email",newActionMessage("error.emailaddress.required"));}//SavestheerrorsaveErrors(request,errors);//Forwardthepageif(errors.isEmpty()){returnmapping.findForward("success");}else{returnmapping.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.

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):

packageroseindia.net;

importorg.apache.struts.action.*;importorg.apache.struts.upload.FormFile;

/***@authorDeepakKumar*@Webhttp://www.roseindia.net*@[email protected]*/

/***FormbeanforStrutsFileUpload.**/publicclassStrutsUploadFormextendsActionForm{privateFormFiletheFile;

/***@returnReturnsthetheFile.*/publicFormFilegetTheFile(){returntheFile;}/***@paramtheFileTheFormFiletoset.*/publicvoidsetTheFile(FormFiletheFile){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):

packageroseindia.net;

importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;

importorg.apache.struts.action.Action;importorg.apache.struts.action.ActionForm;importorg.apache.struts.action.ActionForward;importorg.apache.struts.action.ActionMapping;importorg.apache.struts.upload.FormFile;/***@authorDeepakKumar*@Webhttp://www.roseindia.net*@[email protected]*/

/***StrutsFileUploadActionForm.**/publicclassStrutsUploadActionextendsAction{publicActionForwardexecute(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{StrutsUploadFormmyForm=(StrutsUploadForm)form;

//ProcesstheFormFileFormFilemyFile=myForm.getTheFile();StringcontentType=myFile.getContentType();StringfileName=myFile.getFileName();intfileSize=myFile.getFileSize();byte[]fileData=myFile.getFileData();System.out.println("contentType:"+contentType);System.out.println("FileName:"+fileName);System.out.println("FileSize:"+fileSize);returnmapping.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:

Defining Action Mapping

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

Developing jsp page

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

Struts File Upload Example

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:

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.9Download 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 StrutsDownload 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 DatabaseIn 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 ApplicationNow 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 ManagerThe 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 element should look like:

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

packagetest;

importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;

importorg.apache.struts.action.Action;importorg.apache.struts.action.ActionForm;importorg.apache.struts.action.ActionForward;importorg.apache.struts.action.ActionMapping;

importjava.sql.*;

publicclassTestDataSourceextendsAction{publicActionForwardexecute(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{

javax.sql.DataSourcedataSource;java.sql.ConnectionmyConnection=null;try{dataSource=getDataSource(request);myConnection=dataSource.getConnection();Statementstmt=myConnection.createStatement();ResultSetrst=stmt.executeQuery("selectusernamefromtest");System.out.println("******************************************");System.out.println("********OutPutfromTestDataSource******");while(rst.next()){System.out.println("UserNameis:"+rst.getString("username"));}System.out.println("******************************************");rst.close();stmt.close();//dowhatyouwishwithmyConnection}catch(SQLExceptionsqle){getServlet().log("Connection.process",sqle);}finally{//enclosethisinafinallyblocktomake//suretheconnectionisclosedtry{myConnection.close();}catch(SQLExceptione){getServlet().log("Connection.close",e);}}

returnmapping.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.xmlNow add the following action mapping into the struts-config.xml:

Running and testingStart 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.

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.

Developing Struts PlugIn

This article shows you how to develop custom Struts PlugIn and incorporate in your Struts Web Applications. After completing this tutorial you will be able to create your own custom PlugIn for your web application. Struts PlugIn allows the programmer to enhance their web applications. There are many PlugIns available for struts e.g. Struts Tiles PlugIn, Struts Hibernate PlugIn, Struts Spring PlugIn etc. Beside these available PlugIn you can create your own PlugIn.

Understanding PlugIn

Struts PlugIns are configured using the element within the Struts configuration file. This element has only one valid attribute, 'className', which is the fully qualified name of the Java class which implements the org.apache.struts.action.PlugIn interface.

For PlugIns that require configuration themselves, the nested element is available.

The plug-in tag in the struts-config.xml file is used to declare the PlugIn to be loaded at the time of server start-up. Following example shows how to declare the Tiles PlugIn:

The above declaration instructs the struts to load and initialize the Tiles plugin for your application on startup.

Writing Struts PlugIn Java Code

In this example we write HelloWorld Struts PlugIn example that will give you idea about creating, configuring and checking Struts PlugIn. Our HelloWorld Stuts PlugIn contains a method called Say Hello, which simply returns HelloWorld message.

Here is code of HelloWorld Struts Plugin:

packageroseindia.net.plugin;

importjavax.servlet.ServletContext;importjavax.servlet.ServletException;importorg.apache.struts.action.PlugIn;importorg.apache.struts.action.ActionServlet;importorg.apache.struts.config.ModuleConfig;

/***@authorDeepakKumar*@Webhttp://www.roseindia.net*@[email protected]*/

publicclassHelloWorldStrutsPluginimplementsPlugIn{

publicstaticfinalStringPLUGIN_NAME_KEY=HelloWorldStrutsPlugin.class.getName();

publicvoiddestroy(){System.out.println("DestroyingHelloWorldPlugIn");}

publicvoidinit(ActionServletservlet,ModuleConfigconfig)throwsServletException{System.out.println("InitializingHelloWorldPlugIn");ServletContextcontext=null;context=servlet.getServletContext();HelloWorldStrutsPluginobjPlugin=newHelloWorldStrutsPlugin();context.setAttribute(PLUGIN_NAME_KEY,objPlugin);

}

publicStringsayHello(){System.out.println("HelloPlugin");return"HelloPlugin";}}

Configuring PlugIn

To configure the plugin add the following line your struts-config.xml file.

Calling PlugIn From JSP Page

Here is the code for calling our PlugIn from jsp page.

Message From Plugin:

Building and Testing

Use ant tool to build the application and then deploy on the server. Enter the url http://localhost:8080/strutstutorial/pages/plugin.jsp in your browser. It display "Hello Plugin" message. Your server console also should display "Hello Plugin" message.

In this section we learnt how to develop simple struts plugin, configure, deploy and test.