Está en la página 1de 44

What is Struts?

Model-View-Controller (MVC) design pattern is used by Struts Framework which is the implementation of the JSP. Struts is open source and is also maintained as a part of Apache Jakarta project. Struts Framework is well suited for application of any size.

Major Versions of Struts


Two major versions of Struts framework is offered by the Apache Struts Project. For the Java,Struts 1 is recognized as the most popular web application framework. The struts 1.x framework is the mature, well-documented, and widely supported. Struts 1 is the best choice for the teams who value proven solutions to common problems. Other name of Struts 2 was WebWork 2. The WebWork and the Struts communities joined forces to create Struts 2 after working independently for several years. For teams who value elegant solutions to difficult problems,the new framework is best choice . In the fourth quarter of the 2006,a stable release of Struts 2 is expected . A BETA release is also available now.

The Six Basic Steps in Using Jakara Struts


1. Modify struts-config.xml. In addition to forward and action elements used to specify the destination URLs and Action object, we use the form-bean element to declare form beans. We also add the scope and name attributes to the action element to tie the form bean to the Action. Optionally, to declare a properties file containing the standard messages, names, and labels,we add a message-resources element .

2. Define a form bean. This bean has the properties (i.e., getter and setter methods) corresponding to each of the incoming request parameters and normally extends ActionForm and . Alternatively,in which case it will contain a Map representing the request parameters, the bean can extend the DynaActionForm.

3. Create results beans. These are normal beans of which is used in MVC when implemented directly with RequestDispatcher. That is, they represent the data access code and results of the business logic. These beans are stored in request, session, or application scope with the use of setAttribute method of HttpServletRequest, HttpSession, or ServletContext, just as in the normal non-Struts applications.

4. Create an Action object to handle requests. Rather than calling request.getParameter explicitly as in the previous example, we can use the execute method casts the ActionForm argument to the specific form bean class, then uses getter methods to access the properties of the object.

5. Create form that invokes blah.do. This form can use the bean:message tag to output text labels and standard messages that are defined in the properties file that is declared with the message-resources in strutsconfig.xml

6. Display results in JSP. The JSP page uses the bean:write tag to output properties of the result bean and form bean . It may also use the bean:message tag to output text labels and standard messages that are defined in standard properties file.

Advantages of Using Struts


y

Centralized File-Based Configuration. Rather than hard-coding information into Java programs, many Struts values are represented in the property or XML files. This loose coupling means that many changes can be made without recompiling or modifying the Java code, and that wholesale changes can be made by editing a single file. This approach also lets Web developers and Java focus on their specific tasks (implementing business logic, presenting certain values to clients, etc.) without needing to know about overall system layout.

Form Beans. In JSP,To automatically populate a JavaBean component based on the incoming request parameters, you can use property="*" with jsp:setProperty . Unfortunately, however, in the standard API this capability is unavailable to the servlets, even though with MVC it is really servlets, not JSP pages, that should usually be the target of form submissions. Apache Struts extends this capability to Java code and adds in several useful utilities, all of which serve to greatly simplify the processing of the request parameters.

Bean Tags. Apache Struts provides a set of custom JSP tags (bean:write, in particular) that let you easily output the properties of JavaBeans component. Basically, these are concise and powerful variations of standard jsp:useBean and jsp:getProperty tags.

HTML Tags. Apache Struts provides a set of custom JSP tags to create HTML forms that are associated with the JavaBeans components. This bean/form association serves two useful purpose:
o o

It lets you get initial form-field values from the Java objects. It lets you to redisplay forms with some or all previously entered values intact.

Form Field Validation. Apache Struts has builtin capabilities for checking that form values are in required format. If values are missing or in an improper format, the form can be automatically redisplayed with the error messages and with the previously entered values maintained. This validation can be performed on server (in Java), or both on server and on client (in JavaScript).

Consistent Approach. Struts encourages consistent use of MVC throughout of your application

Disadvantages of Using Struts


y

Bigger Learning Curve. To use MVC with the standard RequestDispatcher, you need to be comfortable with the standard JSP and servlet API and a large and elaborate framework that is almost equal in size to the core system. This drawback is especially significant with smaller project, nearterm deadlines, and less experienced developers; you could spend as much time learning Struts as building your actual system.

Worse Documentation. Compared to the standard servlets and JSP APIs, Struts has fewer online resources, and many first-time users find the online Apache documentation confusing and poorly organized. There are also fewer books on the Apache Struts than on standard servlets and JSP.

Less Transparent. With Struts applications, there is a lot more going on behind scenes than with normal Java-based Web applications. As a result, Struts applications always are:
o o

Harder to benchmark and optimize Harder to understand

Rigid Approach. The flip side of the benefit that Struts encourages a consistent approach to MVC is that Struts makes it difficult to use other approaches.

What You Should Already Know


Before you goes to this tutorial you should have a basic understanding of the following:
y

HTML

y y y y y

A basic understanding of JAVA JSP Servlets JDBC Custom Tags

If you are going to study these subjects first, find the tutorial on our Home page
//CONTROLLER

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


The Model-View-Controller architecture Model helps to devide an application into three different categories i,e Model, View and the Controller. Components of the MVC architecture is independent of other component and has unique responsibility.Changes in one component will have less or no impact on other components.Responsibilities of the three components are: Model:Model is used for providing the data from the database and saving the data into the data stores.In Model,all the business logic are implemented .Before saving into the database,data entered by the user through View are checked in the model.Data access,the Data saving logic and Data validation are part of the Model. View: View is responsible for the taking the input from the user, dispatching the request to the controller and then receiving response from the controller,displaying the result to the user and represents the user view of the application. HTML, Custom Tag Libraries,JSPs and Resources files are part of the view component. Controller: Controller is intermediary between the View and the Model.For receiving the request from the client,Controller is used. Once request is received from the client it executes the appropriate business logic from the Model and then it uses the View component to produce the output.ActionServlet,ActionForm, Action, and struts-config.xml are part of the Controller.

The above figure is the MVC architecture 2 model which uses by the Struts.

Setting Up Development Environment Installing JDK:


From the sun site,download JDK 1.4 or above . Use the instruction given in installation manual and install JDK.

Installing Tomcat:
Go to the apache site and then download Tomcat and install it. I have downloaded jakartatomcat-5.0.4 and installed for this tutorial only. To test your installation go to your installation directory/bin and to run server,issue startup command .To test the server,open the browser and type http://localhost:8080/ . The browser should display the welcome page. If not before going further,consult the tomcat documentation .

Installing Struts Application:


Go to the official site of Struts and then download latest version of the Struts http://jakarta.apache.org/struts. Extract the file into your own directory and copy struts-

blank.war, struts-example.war and struts-documentation.war from the "jakarta-struts1.1\webapps" directtory into "jakarta-tomcat-5.0.4\webapps" directory. struts-blank.war is useful in creating the struts application from scratch and also the blank struts application .To create our web applications, we will use this file. struts-documentation.war important documents for the struts application development and also contains the API and struts-example.war is the simple MailReader Demonstration Application

Developing First Struts Application


Go to the jakarta-tomcat-5.0.4\webapps and then rename struts-blank.war to struts-tutorial.war and copy it to the "jakarta-tomcat-5.0.4\webapps" directory. Tomcat loads the application and automatically extract the file.

What is Action Class?


The Action Class is a wrapper around the business logic and is a part of Model.
ADVERTISEMENT

The purpose of using Action Class is to translate the HttpServletRequest to the business logic.To use Action we need to overwrite the execute() method and Subclass. All database/business processing are done in the Action Class.Action Class is used perform all the database related stuffs. Using execute() methodthe ActionServlet (commad) passes the parameterized class to Action Form.Struts Framework uses execute method to forward the request to the file as per the value of the returned ActionForward object.The return type of execute method is ActionForward

How to Develop Action Class?


Action class is used to forward the TestAction.jsp. In our action classit returns ActionForward called "testAction" which is defined in the struts-config.xml file (action mapping is show later in this page). The following example called TestAction.java is the action class package academictutorilal.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


The signature of the Action Class is as follows. public ActionForward execute(ActionMapping mapping ActionForm form javax.servlet.http.HttpServletRequest request javax.servlet.http.HttpServletResponse response) throws java.lang.Exception Action Class is used to process the specified HTTP requestand create the corresponding HTTP response (or forward to another web component that will create it)with provision for the handling exceptions thrown by the business logic.Where and how control should be forwarded or null if the response has already completed is done with use of ActionForward instance.

Parameters of Action Class


mapping The ActionMapping parameter form The optional ActionForm request The HTTP request response The HTTP response Throws: Action class uses throws java.lang.Exceptionif application business logic throws an exception used to select this instance bean for this request that we are processing that we are creating

Adding the Action Mapping in the struts-config.xml


To test the application we will add a <html:link page="/TestAction.do">Test the Action</html:link> link in index.jsp

The following code under the <action-mappings> tag is used for mapping TestAction class.
<action path="/TestAction" type="academictutorials.net.TestAction"> <forward name="testAction" path="/pages/TestAction.jsp"/> </action> Click on Test the Action link on the index page if you want to test the new applications. On the user browserthe content of TestAction.jsp should be displayed .

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

At first,we will first create the class called AddressForm which extends the ActionForm class.The following code describes ActionForm.java. package academictutorials; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.*; /** * 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() < 1 ) { errors.add("name",new ActionMessage("error.name.required")); } if( getAddress() == null || getAddress().length() < 1 ) { errors.add("address",new ActionMessage("error.address.required")); } if( getEmailAddress() == null || getEmailAddress().length() < 1 )

{ errors.add("emailaddress",new ActionMessage("error.emailaddress.required")); } return errors; } }

The above class validates Address Form data and populates it. To validate user inputs,the validate() method is used . Error messages are added to ActionMapping object,if any or all of the fields on the form are blank . Note that in the next version ActionError will be removed and now we are using ActionMessage class. Now we will create the model part of the application called Action class. In our action class simply forwards request to the Success.jsp. The following example is the code for AdessAction.java class package academictutorials; 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"); } }

In the struts-config.xml,we have to create an entry for form bean. In struts-config.xml file,add the following lines :

<form-bean name="AddressForm" type="academictytorials.AddressForm"/> In struts-config.xml file,add the following line for handling the action "/Address.do": <action path="/Address" type="roseindia.net.AddressAction" name="AddressForm" scope="request" validate="true" input="/pages/Address.jsp"> <="" td=""> For entering the address details,create the Address.jsp page which is our form . Code for Address.jsp is as follows: <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <html:html locale="true"> <head> <title><bean:message key="welcome.title"/></title> <html:base/> </head> <body bgcolor="white"> <html:form action="/Address"> <html:errors/> <table> <tr> <td align="center"> <font size="4">Please Enter the Following Details</font> </tr> <tr> <td align="right"> Name </td> <td align="left"> <html:text property="name" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right">

Address </td> <td align="left"> <html:text property="address" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> E-mail address </td> <td align="left"> <html:text property="emailAddress" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <html:submit>Save</html:submit> </td> <td align="left"> <html:cancel>Cancel</html:cancel> </td> </tr> </table> </html:form> </body> </html:html> At first,the user enters the values in the form and then click on submit form. On the server side,form validation is done.The Eeror message is displays on the jsp page . Use the following code to display the error on the jsp page the <html:errors/> > tag is used. The <html:errors/> tag displays all the errors in one go. To create text box the <html:text .../> nbsp; e.g. <html:text property="address" size="30" maxlength="30"/> To enter the address,the above tag is used.In form-bean,the address is retrieved from and later stored in the property named address. Using <html:submit>Save</html:submit> tag we ca create the submit button and using <html:cancel>Cancel</html:cancel> tag we can create Cancel button. To create a link for testing the Address.jsp form,add the following line in index.jsp. <html:link page="/pages/Address.jsp">Test Address Form</html:link>

To test the newly created screen,build the application and click on the Test the Address Form link on the index page .

Struts HTML Tags


For easy creation of user interfaces,struts provides the HTML tag library .For the development of user interfaces,in this lesson I will show you what all Struts HTML Tags are available to JSP.
ADVERTISEMENT

At first we have to include following line in our JSP file to use the Struts HTML Tags : <%@ taglib uri="/tags/struts-html" prefix="html" %> above code makes available the tag to jsp.

The following table shows the different HTML tags available in struts
Struts HTML Tags <html:message key="thekey"/> <html:password property="prop" size="10"/> <html:text property="text1" size="5"/> <html:submit>Submit</html:submit> <html:reset>Reset</html:reset> <html:errors/> <html:file property="fileSelectionBox"/> <html:checkbox property="myCheckBox"/> <html:hidden property="hiddenfield"/> Description 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. Tag creates a submit button with the provided content as the button text. 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.

<html:radio value="abc" property="myCheckBox"/> <html:select multiple="true" property="selectBox"> <html:textarea property="myTextArea" value="Hello Struts" /> <html:form action="/Address" method="post">

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 <html:options> 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. <BASE ...> 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 <BASE HREF="..."> instead of the actual URL. <BASE ...> goes in the <HEAD> section. Tag renders an HTML <html> Element.

<html:base/>

<html:html>

In the Address.jsp which is in previour page we have used some of above tags

Struts Validator Framework


To validate the form data,Struts Framework provides the functionality.
ADVERTISEMENT

It can be use to validate the data on client side as well as on the server side. Struts Framework can be used to validate the form data on the client browser and emits java scripts.By sub classing your From Bean with the DynaValidatorForm class,server side validation of the form can be accomplished . David Winterfeldt developed the Validator framework as third-party add-on to the Struts.Now the Validator framework can be used with or without the Struts and it is a part of Jakarta Commons project .The Validator framework can be used without doing any extra settings and comes integrated with Struts Framework.

Using Validator Framework


To pickup validation rules to be applied to an form,validator uses the XML file. In XML

validation requirements are applied to the form and aslo can be defined.In validator framework,we can plug in our own custom validations into Validator. The Validator Framework uses two XML configuration files called validator-rules.xml and validation.xml. Standard validation routines are defined by the validator-rules.xml and used in validation.xml. To define form specific validations,validation.xml is used.To define the validations applied to a form bean,the validation.xml

Structure of validator-rule.xml
The validation-rules.xmldeclares and assigns the logical names to the validation routines and is provided with Validator Framework. For each validation routine,it also contains client-side javascript code . To perform specific validations,the validation routines are the java methods plugged into the system . Following table contains the details of the elements in this file: Element Attributes and Description

formThis is the root node. It contains nested elements for all of the other configuration validation settings. global The validator details specified within this, are global and are accessed by all forms. The validator element defines what validators objects can be used with the fields referenced by the formset elements. The attributes are:
y y y y y

validator

y y

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.

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 javascript commons-validator. The default can be overridden by supplying a <javascript> element with a CDATA section, just as in struts 1.1. The Validator plug-in which is also known as validator-rules.xml is supplied with the predefined set of commonly used validation rules such as Required, Minimum Length, Maximum length, Date Validation, Email Address validation and more. If required,this basic set of rules can also be extended with the custom validators .

Structure of validation.xml
This validation.xml configuration file define which validation routines that is used to validate Form Beans and also you can define validation logic for any number of Form Beans in this configuration file . Inside that definition, you specify validations you want to apply to the Form Bean's fields and the definition in this file use the logical names of Form Beans from the strutsconfig.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together. The following table shows the elements of the validation.xml file Element formvalidation global constant constantname constantvalue formset Attributes and Description This is the root node. It contains nested elements for all of the other configuration settings The constant details are specified in <constant> element within this element. Constant properties are specified within this element for pattern matching. Name of the constant property is specified here Value of the constant property is specified here. This element contains multiple <form> elements 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.

form

The attributes are:


y y

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 var var-name var-value

A key for the error message to be thrown incase the validation fails, is specified here Contains the variable names and their values as nested elements within this element. The name of the criteria against which a field is validated is specified here as a variable The value of the field is specified here

Example of form in the validation.xml file is as follows:


<!-- An example form --> <form name="logonForm"> <field property="username" depends="required"> <arg key="logonForm.username"/> </field> <field property="password" depends="required,mask"> <arg key="logonForm.password"/> <var> <var-name>mask</var-name> <var-value>^[0-9a-zA-Z]*$</var-value> </var> </field> </form> To allow front-end validation based on xml in validation.xml,the <html:javascript> tag is used.In the validation.xml file,for example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generate the client side java script for the form "logonForm" . The <html:javascript> generates the client site validation script when added in jsp file.

Address Validation in Struts


ADVERTISEMENT

To validates the user input on the browser,validator Framework emits the JavaScript code. Follow these steps to accomplish this: 1. Enabling the Validator plug-in: This makes Validator available to the system itself. 2. Create Message Resources To display error message to the user. 3. Developing the Validation rulesIn validation.xml,we have to define the validation rules for the address form. Struts Validator Framework uses this rule for generating JavaScript for validation. 4. Applying the rules: For generation of JavaScript,we are required to add the appropriate tag to JSP. 5. Build and test: Before the testing,we are required to build the application once the above steps are done .

Enabling the Validator plug- in


Enabling the Validator plug- in is used to enable validator plug-in open the file struts-config.xml and make sure that following line is present in the file. <!-- Validator plugin --> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/> </plug-in>

Creating Message Resources


To generate the validation error,messagesMessage resources are used by Validator Framework . We need to define the message for name,Address and E-mail address in our application. Add following lines: AddressForm.name=Name AddressForm.address=Address AddressForm.emailAddress=E-mail address into the Struts\strutstutorial\web\WEB-INF\MessageResources.properties file.

Developing Validation rules

We are adding only one validation that fields on the form should not be blank in this application. Add the following code in validation.xml to validate the form. <!-- Address form Validation--> <form name="AddressForm"> <field property="name" depends="required"> <arg key="AddressForm.name"/> </field> <field property="address" depends="required"> <arg key="AddressForm.address"/> </field> <field property="emailAddress" depends="required"> <arg key="AddressForm.emailAddress"/> </field> </form> The above example defines validation for the form fields name, address and emailAddress. To check that the fields are not left blank,the attribute depends="required" is used to instructs Validator Framework to generate the JavaScript .JavaScript shows error message,if the fields are left blank .The message are taken from the key defined in <arg key=".."/> tag in the error message.We can take the value from message resources (Struts\strutstutorial\web\WEBINF\MessageResources.properties).

Applying Validation rules to JSP


To test the application just create AddressJavascriptValidation.jsp file . The following file called AddressJavascriptValidation.jsp is as follows: <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <html:html locale="true"> <head> <title><bean:message key="welcome.title"/></title> <html:base/> </head> <body bgcolor="white"> <html:form action="/AddressJavascriptValidation" method="post" onsubmit="return validateAddressForm(this);"> <div align="left">

<p> This application shows the use of Struts Validator.<br> The following form contains fields that are processed by Struts Validator.<br> Fill in the form and see how JavaScript generated by Validator Framework validates the form. </p> <p> <html:errors/> </p> <table> <tr> <td align="center" colspan="2"> <font size="4"><b>Please Enter the Following Details</b></font> </tr> <tr> <td align="right"> <b>Name</b> </td> <td align="left"> <html:text property="name" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <b>Address</b> </td> <td align="left"> <html:text property="address" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <b>E-mail address</b> </td> <td align="left"> <html:text property="emailAddress" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <html:submit>Save</html:submit>

</td> <td align="left"> <html:cancel>Cancel</html:cancel> </td> </tr> </table> </div> <!-- Begin Validator Javascript Function--> <html:javascript formName="AddressForm"/> <!-- End of Validator Javascript Function--> </html:form> </body> </html:html> To plug-in Validator JavaScript,the code <html:javascript formName="AddressForm"/> is used . In struts-config.xml,create the following entry for the mapping the /AddressJavascriptValidation url for handling the form submission through AddressJavascriptValidation.jsp. <action path="/AddressJavascriptValidation" type="roseindia.net.AddressAction" name="AddressForm" scope="request" validate="true" input="/pages/AddressJavascriptValidation.jsp"> <forward name="success" path="/pages/success.jsp"/> </action> To call the form,add the following line in index.jsp. <li> <html:link page="/pages/AddressJavascriptValidation.jsp">Client Side Validation for Address Form</html:link> <br> The Address Form that validates the data on the client side using Stuts Validator generated JavaScript. </li>

Building Example and Testing


Go to Struts\strutstutorial directory and type ant on the command prompt to build and deploy application. This will use to deploy the application.Then open the browser and navigate to AddressJavascriptValidation.jsp page. Your browser should shows the following output.

Browser shows the error message,if the fields are left blank and Save button is clicked,

What is Struts Tiles?


y

To development user interface,Tiles framework is used. By assembling the reusable tiles (jsp, html, etc..),tiles is enables the developers to develop web applications.

ADVERTISEMENT

Tiles nables the developers to define a template for web site and uses the concept of reuse and then use this layout to populate the content of the web site.

Steps To Create Tiles Application


To develop of web application,tiles framework is used. Follow these steps for adding Tiles to your Struts applications: 1. 2. 3. 4. At first,add the Tiles Tag Library Descriptor (TLD) file to web.xml. Then create the layout JSPs. After that develop web pages using layouts. Then repackage, run and test the application.

Add the Tiles TLD to web.xml file


Tiles can can be used without or with the Struts. Before you can use the tiles tags in your application,Following entry is required in web.xml file. <taglib> <taglib-uri>/tags/struts-tiles</taglib-uri> <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location> </taglib>

Create layout JSPs


Suppose our web application layout is divided into the four parts called Top Banner, Left Navigation Bar,Content Area and Bottom of the page for copy right information. The following file is the code of template.jsp: <%@ page language="java" %> <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %> <html> <head> <title><tiles:getAsString name="title" ignore="true"/></title> </head> <body>

<table border="1" cellpadding="0" cellspacing="0" width="100%" bordercolor="#000000" bgcolor="#E7FDFE"> <tr> <td width="100%" colspan="2" valign="top"><tiles:insert attribute="header"/></td> </tr> <tr> <td width="23%"><tiles:insert attribute="menu"/></td> <td width="77%" valign="top" valign="top"><tiles:insert attribute="body"/></td> </tr> <tr> <td width="100%" colspan="2" valign="top"><tiles:insert attribute="bottom"/></td> </tr> </table> </body> </html> You can use the appropriate html to define structure for web application and did the following things: Referenced /WEB-INF/struts-tiles.tld TLD file. To display the title using the tiles:getAsString tag,use the string parameters. Ignore missing parameter ,if the attribute ignore="true" then Tiles. If this is true in case the parameter is missing then the Tiles framework will through exception . The tiles:insert tag is used to insert the contents JSP, which inserts any page or web resources that framework refers to as a title. For Example <tiles:insert attribute="header"/> inserts header web page.

Develop the web pages using layouts


In our application,we will use tile layout create a page to display the content page . There is additional jsp file for inserting the content in Layout for every content page. So we have to create two jsp files one for displaying the content and another for the content. In our example we have used two files example.jsp and content.jsp. The following example is the code for contents.jsp and example.jsp files: <p align="left"><font color="#000080" size="5">Welcome to the Title Tutorial</font></p> <p align="left"><font color="#000080" size="5">This is the content page</font></p> The content.jsp is used to define the content of the page. The content may be static or dynamic depending on requirements. <%@ page language="java" %> <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

<tiles:insert page="/tiles/template.jsp" flush="true"> <tiles:put name="title" type="string" value="Welcome" /> <tiles:put name="header" value="/tiles/top.jsp" /> <tiles:put name="menu" value="/tiles/left.jsp" /> <tiles:put name="body" value="/tiles/content.jsp" /> <tiles:put name="bottom" value="/tiles/bottom.jsp" /> </tiles:insert> The code <tiles:insert page="/tiles/template.jsp" flush="true"> specify the tiles layout page to be used. We have set the flush attribute to true, this makes tile file to be written to browser before the rest of the page. To specify the title of page <tiles:put name="title" type="string" value="Welcome" /> is used. The following code is used to insert actual pages in the template.: <tiles:put name="header" value="/tiles/top.jsp" /> <tiles:put name="menu" value="/tiles/left.jsp" /> <tiles:put name="body" value="/tiles/content.jsp" /> <tiles:put name="bottom" value="/tiles/bottom.jsp" /> The content.jsp wil be inserted in the layout's body region and the bottom.jsp will be inserted in bottom region.The top.jsp will be inserted in the layout's header of the region. The left.jsp will be inserted in layout's menu region. .

Repackage, run and test application


To test this tile example,add the following code in the index.jsp: <li> <html:link page="/tiles/example.jsp">Tiles Example</html:link> <br> Example of creating first tile application. </li>
y

T o generate the output in Tiles we can define the definition in tiles-defs.xml which specifies the different components to "plugin" .

ADVERTISEMENT

We can eliminates the need to define extra jsp file for the each content file by using tilesdefs.xml.

For example,we have defined example.jsp to display the content of the content.jsp file in the last section.

In this section I will show you using the tiles-defs.xml file how to eliminate the need of extra jsp file.

Steps to Use the tiles-defs.xml Setup the Tiles plugin in the struts-config.xml file.
In struts-config.xml,add the following code. We use the /WEB-INF/tiles-defs.xml file to enable TilesPlugin <plug-in className="org.apache.struts.tiles.TilesPlugin" > <!-- Path to XML definition file --> <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" /> <!-- Set Module-awareness to true --> <set-property property="moduleAware" value="true" /> </plug-in>

Defining the tiles-defs.xml


In this file we are defining different components to the "plugin" tag. The following is th code for the same: <definition name="Tiles.Example" page="/tiles/template.jsp"> <put name="title" type="string" value="Welcome" /> <put name="header" value="/tiles/top.jsp" /> <put name="menu" value="/tiles/left.jsp" /> <put name="body" value="/tiles/content.jsp" /> <put name="bottom" value="/tiles/bottom.jsp" /> </definition> The page attribute define the template file to be used and the put tag specifies the different components to "plugin".The name of the definition is Tiles.Example,we will use this in the struts-config.xml (While creating forwards in struts-config.xml file) file Your tiles-defs.xml

should looks like: <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd"> <tiles-definitions>

<definition name="Tiles.Example" page="/tiles/template.jsp"> <put name="title" type="string" value="Welcome" /> <put name="header" value="/tiles/top.jsp" /> <put name="menu" value="/tiles/left.jsp" /> <put name="body" value="/tiles/content.jsp" /> <put name="bottom" value="/tiles/bottom.jsp" /> </definition> <definition name="${YOUR_DEFINITION_HERE}"> </definition> </tiles-definitions>

Configure the Struts Action to use Tiles Definition


Add following code in the struts-config.xml : <action path="/Tiles/Example" forward="Tiles.Example"/> In the above code,with Tiles,the action points to Tiles definition.we are using Tiles.Example in this code definition which we have defined in the tiles-defs.xml file. Without Tiles,forward and action definitions point directly to the JSPs. With Tiles,they point to the page's definition in Tiles configuration file. Testing the Application To call the Example,Create a link in the index.jsp.Code added are as follows: <li> <html:link page="/Tiles/Example.do">Using tiles-defs.xml</html:link> <br> Example shows you how to use tiles-defs.xml file. </li>

Dynamic Action Form


y

DynamicActionForm eliminates the need of the FormBean class.The form bean definition can be written into the struts-config.xml file.

To reduce the development time for the developer,it makes FormBean declarative .

ADVERTISEMENT

To create a Java class for each type of form bean,DynamicActionForm is used as the specialized subclass of ActionForm that allows the creation of the form beans with dynamic sets of properties, without requiring the developer.

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

Adding DynaActionForm Entry in struts-config.xml


At First,in the struts-config.xml file we will add necessary entry . The form bean is of the org.apache.struts.action.DynaActionForm type. To define the property for form bean,the <formproperty/> tag is used . Three properties for our dynamic form bean. <form-bean name="DynaAddressForm" type="org.apache.struts.action.DynaActionForm"> <form-property name="name" type="java.lang.String"/> <form-property name="address" type="java.lang.String"/> <form-property name="email" type="java.lang.String" /> </form-bean>

Adding action mapping


In struts-config.xml file,add the following action mapping <action path="/DynaAddress" type="roseindia.net.AddressDynaAction"

name="DynaAddressForm" scope="request" validate="true" input="/pages/DynaAddress.jsp"> <forward name="success" path="/pages/success.jsp"/> <forward name="invalid" path="/pages/DynaAddress.jsp" /> </action>

Creating Action Class


The following code is for the action class: package academictutorials; 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


In the jsp file,we will use the Dyna Form DynaAddressForm created above . The following example is the code of jsp(DynaAddress.jsp) file <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <html:html locale="true"> <head> <title><bean:message key="welcome.title"/></title> <html:base/> </head> <body bgcolor="white"> <html:form action="/DynaAddress" method="post"> <table> <tr> <td align="center" colspan="2"> <font size="4">Please Enter the Following Details</font> </tr>

<tr> <td align="left" colspan="2"> <font color="red"><html:errors/></font> </tr>

<tr> <td align="right"> Name </td> <td align="left"> <html:text property="name" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> Address </td> <td align="left"> <html:text property="address" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> E-mail address </td> <td align="left"> <html:text property="email" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <html:submit>Save</html:submit> </td> <td align="left"> <html:cancel>Cancel</html:cancel> </td> </tr> </table>

</html:form> </body> </html:html> In index.jsp,add the following line to call the form. <li> <html:link page="/pages/DynaAddress.jsp">Dyna Action Form Example</html:link> <br> Example shows you how to use DynaActionForm. </li>

Building Example and Testing


Go to Struts\strutstutorial directory and type ant on the command prompt to build and deploy application. This will help to deploy application. Open the browser and type DynaAddress.jsp page. In the form,without entering anything and submitting the submit button.

How to Upload a file in Struts


To upload a file,the interface org.apache.struts.upload.FormFile is used in the application. To represents a file that has been uploaded by the client,this interface is used.
ADVERTISEMENT

It is the only class or interface in the upload package which is typically referenced directly by a Struts application

Creating Form Bean


In our example,the form bean class contains one property theFile, which is of type org.apache.struts.upload.FormFile. The following example is the code of the FormBean (StrutsUploadForm.java): package academictutorials; import org.apache.struts.action.*; import org.apache.struts.upload.FormFile; /** * 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


To retrieve the reference of the uploaded file,the action class simply calls getTheFile() function on the FormBean object. To get uploaded file and its information, the reference of the FormFile is used . The following is code of our action class called strutsUploadAction.java: package academictutorials; 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; /** * 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


In struts-config.xml file for defining the form bean,add the following entry. <form-bean name="FileUpload" type="academictutorials.StrutsUploadForm"/>

Defining Action Mapping


In struts-config.xml file,add the following action mapping entry : <action path="/FileUpload" type="academictutorials.StrutsUploadAction" name="FileUpload" scope="request" validate="true" input="/pages/FileUpload.jsp">

<forward name="success" path="/pages/uploadsuccess.jsp"/> </action>

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" %> <html:html locale="true"> <head> <title>Struts File Upload Example</title> <html:base/> </head> <body bgcolor="white"> <html:form action="/FileUpload" method="post" enctype="multipart/form-data"> <table> <tr> <td align="center" colspan="2"> <font size="4">Please Enter the Following Details</font> </tr> <tr> <td align="left" colspan="2"> <font color="red"><html:errors/></font> </tr>

<tr> <td align="right"> File Name </td> <td align="left"> <html:file property="theFile"/> </td> </tr>

<tr> <td align="center" colspan="2"> <html:submit>Upload File</html:submit>

</td> </tr> </table>

</html:form> </body> </html:html> Note that we have set the encrypt property of form to enctype="multipart/form-data". The following code for the success page (uploadsuccess.jsp) is as follows: <html> <head> <title>Success</title> </head> <body> <p align="center"><font size="5" color="#000080">File Successfully Received</font></p> </body> </html>

In index.jsp to call the form,add the following line. <li> <html:link page="/pages/FileUpload.jsp">Struts File Upload</html:link> <br> Example shows you how to Upload File with Struts. </li>

Building Example and Testing


Go to Struts\strutstutorial directory and type ant on the command prompt,to build and deploy application. This will help to deploy application. Open the browser and type FileUpload.jsp page. Your browser should display the file upload form as follows:

Struts Database Connection Using Mysql Database


ADVERTISEMENT

In this tutorial to use MySQL Database ,we will configure the Struts DataSource Manager and use the connection provided by Struts DataSource in action class.

Downloading and Installing Tomcat 5.5.9


Go to http://jakarta.apache.org/tomcat/. Down load the Tomcat 5.5.9 Install it into your machine.Test and run the pages that comes with tomcat.

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

Download MySQL JDBC Driver


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

JDBC driver to the tomcat server.

Creating MySQL Database


I am using MySQL server installed on my local machine in this tutorial . You can install and download the MySQL on your local machine and use for this tutorial and if you already have the MySQL server then you can use the existing MySQL server. To create test table,create database "strutsdatabase" on the MySQL server and then run following query. 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 is used to create test table and then populates the table with the data.

Configuring Struts Application


In the strutsdatabase directory,create a directory "strutsdatabase" in jakarta-tomcat5.5.9\webapps\ directory and copy the content of struts-blank application (unzipped above) . Now start tomcat and by typing the url try to access the strutsdatabase application http://localhost:8080/strutsdatabase in browser. Your browser should display welcome page. After testing shutdown tomcat server.

Configuring Struts DataSource Manager


It is easy for your Action class get database connection using the Struts DataSource manager.In the struts-config.xml,to configure the Stuts DataSource Manager we will uncomment <datasources> entry . In struts-config.xml,uncomment <data-sources> 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 the naming-factory-dbcp.jar archieve, so instead of "org.apache.commons.dbcp.BasicDataSource" we are using "org.apache.tomcat.dbcp.dbcp.BasicDataSource". After this in the <data-sources> tag,change database dirver, database url and passwor. You <data-source> attributes are as follows: <data-sources> <data-source type="org.apache.tomcat.dbcp.dbcp.BasicDataSource"> <set-property property="driverClassName" value="com.mysql.jdbc.Driver" /> <set-property property="url" value="jdbc:mysql://localhost:3306/strutsdatabase?autoReconnect=true" /> <set-property property="username" value="root" /> <set-property property="password" value="" /> <set-property property="maxActive" value="10" /> <set-property property="maxWait" value="5000" /> <set-property property="defaultAutoCommit" value="false" /> <set-property property="defaultReadOnly" value="false" /> <set-property property="validationQuery" value="SELECT COUNT(*) FROM test" /> </data-source> </data-sources>

Create action Class to Test the DataSource


To get the connection form DataSource, we will write the following code of the Action class :

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"); } } To get the data source,following code is used and then connection from the Struts DataSource: dataSource = getDataSource(request); myConnection = dataSource.getConnection();

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

Creating Action Mapping struts-config.xml


In struts-config.xml,add the following action mapping : <action path="/DataSource" type="test.TestDataSource"> <forward name="success" path="/success.jsp"/> </action>

Running and testing

Start the tomcat and then browse the url http://localhost:8080/strutsdatabase/DataSource.do.

También podría gustarte