You are on page 1of 113

5154473731

5151096011

Switch action Example in struts

Here I am explaining how to do switch action and how to use more than one config files in struts.

Switchform
package com.switchdispatch; import org.apache.struts.action.ActionForm; /** * * @author Prasanthi * */ public class Switchform extends ActionForm{ int n1; int n2; String method; public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public int getN1() { return n1; } public void setN1(int n1) { this.n1 = n1; } public int getN2() { return n2; } public void setN2(int n2) { this.n2 = n2; }

Switchaction
package com.switchdispatch; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; /** * * @author Prasanthi * */ public class Switchaction extends DispatchAction{ public ActionForward add(ActionMapping map,ActionForm form,HttpServletRequest req,HttpServletResponse res) { Switchform l1=(Switchform)form; int n1=l1.getN1(); int n2=l1.getN2(); HttpSession ses=req.getSession(); int tot=n1+n2; ses.setAttribute("tot",Integer.toString(tot)); return map.findForward("add"); } public ActionForward delete(ActionMapping map,ActionForm form,HttpServletRequest req,HttpServletResponse res) { Switchform l1=(Switchform)form; int n1=l1.getN1(); int n2=l1.getN2();

HttpSession ses=req.getSession(); int tot=n1-n2; ses.setAttribute("del",Integer.toString(tot)); return map.findForward("delete"); } }

Testform
package com.switchdispatch; import org.apache.struts.action.ActionForm; /** * * @author Prasanthi * */ public class TestForm extends ActionForm{ String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }

Testaction
package com.switchdispatch; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; /** * * @author Prasanthi * */ public class TestAction extends Action{ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { TestForm form1=(TestForm)form; String msg=form1.getMsg(); return(mapping.findForward("success")); } }

struts-config.xml
<struts-config> <form-beans> <form-bean name="switchform" type="com.switchdispatch.Switchform" /> </form-beans> <action-mappings> <action path="/switch" type="org.apache.struts.actions.SwitchAction"/> <action path="/switchtest" type="com.switchdispatch.Switchaction" name="switchform" input="/SwitchTest.jsp"

parameter="method"> <forward name="add" path="/switch.do?page=/test1.do&prefix=/test" contextRelative="true" redirect="true"/> <forward name="delete" path="/delete.jsp" contextRelative="true" redirect="true"/> </action> </action-mappings> </struts-config> test-config.xml <struts-config> <form-beans> <form-bean name="testform1" type="com.switchdispatch.TestForm"/> </form-beans> <action-mappings> <action path="/test1" name="testform1" input="/test1.jsp" type="com.switchdispatch.TestAction" scope="request"> <forward name="success" path="/hello.jsp" contextRelative="true" redirect="true" /> </action> </action-mappings> </struts-config>

web.xml
<web-app> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>config/test</param-name>

<param-value>/WEB-INF/test-config.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>SwitchTest.jsp</welcome-file> </welcome-file-list> <taglib> <taglib-uri>/tags/struts-html</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> <taglib> <taglib-uri>/tags/struts-bean</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> </taglib> </web-app>

Switchtest.jsp
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%> <%@ taglib uri="/tags/struts-bean" prefix="bean"%> <html:html> <body> <html:form action="/switchtest"> <center>Add will switch to test-config.xml.<br> <h2><u>Switch Form</u></h2><br> <br> Number1:<html:text property="n1" value=""/><br><br> Number2:<html:text property="n2" value=""/><br><br> Select<select name="method" > <option value="add">Add</option> <option value="delete">Delete</option> <br/> </select>

<html:submit/> </html:form> </body> </html:html>

add.jsp
<html> <center> In ADD Action<br> <% String st=(String)session.getAttribute("tot");%> Total is <%=st%> </html>

delete.jsp
<html> <center>In Delete Action<br> <% String st=(String)session.getAttribute("del");%> After Subtraction <%=st%> </html>

hello.jsp
<br><br> <center> <h2>Welcome To Switch Action</h2>

Struts provides HTML tag library for easy creation of user interfaces.

Struts HTML Tags

Struts provides HTML tag library for easy creation of user interfaces. In this lesson I will show you what all Struts HTML Tags are available to the JSP for the development of user interfaces. To use the Struts HTML Tags we have to include the following line in our JSP file: <%@ taglib uri="/tags/struts-html" prefix="html" %> above code makes available the tag to the jsp.

Struts HTML Tags


<html:message key="thekey"/> 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.

<html:password property="prop" size="10"/> <html:text property="text1" size="5"/>

<html:submit>Submit</html:submit> Tag creates a submit button with the provided content as the button text. <html:reset>Reset</html:reset> Tag creates a reset button with the provided content as the button text. Tag prints all the available error on the page. Tag creates the file upload element on the form. The property must be of the type org.apache.struts.upload.FormFile. Tag creates check box on the form.

<html:errors/> <html:file property="fileSelectionBox"/> <html:checkbox property="myCheckBox"/> <html:hidden property="hiddenfield"/> <html:radio value="abc" property="myCheckBox"/> <html:select multiple="true" property="selectBox">

Tag creates the hidden html element on the form.

Tag creates the check box on the form.

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

<html:textarea property="myTextArea" value="Hello Struts" /> <html:form action="/Address" method="post"> <html:base/>

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

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

his lesson introduces you the Struts Validator Framework.

Struts Validator Framework

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

Introduction to Validator Framework


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

Using Validator Framework


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

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

Structure of validator-rule.xml
The validation-rules.xml is provided with the Validator Framework and it declares and assigns the logical names to the validation routines. It also contains the client-side javascript code for each validation routine. The validation routines are java methods plugged into the system to perform specific validations. Following table contains the details of the elements in this file: Element form-validation global validator Attributes and Description This is the root node. It contains nested elements for all of the other configuration settings. 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:


name: Contains a logical name for the validation routine classname: Name of the Form Bean class that extends the subclass of ActionForm class method: Name of the method of the Form Bean class methodParams: parameters passed to the method msg:Validator uses Struts' Resource Bundle mechanism for externalizing error messages. Instead of having hard-coded error messages in the framework, Validator allows you to specify a key to a message in the ApplicationResources.properties file that should be returned if a validation fails. Each validation routine in the validator-rules.xml file specifies an error message key as value for this attribute. depends: If validation is required, the value here is specified as 'required' for this attribute. jsFunctionName: Name of the javascript function is specified here.

javascript

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

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

Structure of validation.xml

This validation.xml configuration file defines which validation routines that is used to validate Form Beans. You can define validation logic for any number of Form Beans in this configuration file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together. Element form-validation global constant constant-name constant-value formset form 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 This element is inside the form element, and it defines the validations to apply to specified Form Bean fields. The attributes are:

field

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:

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

The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script. In the next lesson we will create a new form for entering the address and enable the client side java script with the Validator Framework.

Client Side Address Validation in Struts Posted on: February 12, 2008 at 12:00 AM In this lesson we will create JSP page for entering the address and use the functionality provided by Validator Framework to validate the user data on the browser.

Client Side Address Validation in Struts

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

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

<!-- 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 Message resources are used by the Validator Framework to generate the validation error messages. In our application we need to define the messages for name, Address and E-mail address. Open the Struts\strutstutorial\web\WEB-INF\MessageResources.properties file and add the following lines:

AddressForm.name=Name AddressForm.address=Address AddressForm.emailAddress=E-mail address Developing Validation rules In this application we are adding only one validation that the fields on the form should not be blank. Add the following code in the validation.xml.

<!-- 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 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 <arg key=".."/> tag. The value of key is taken from the message resources (Struts\strutstutorial\web\WEB-INF\MessageResources.properties). Applying Validation rules to JSP Now create the AddressJavascriptValidation.jsp file to test the application. The code for AddressJavascriptValidation.jsp is as follows:

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <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>

The code <html:javascript formName="AddressForm"/> 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.

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

Add the following line in the index.jsp to call the form. <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 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.

Client Side Address Validation in Struts Posted on: February 12, 2008 at 12:00 AM In this lesson we will create JSP page for entering the address and use the functionality provided by Validator Framework to validate the user data on the browser.

Client Side Address Validation in Struts

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

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

5. Build and test: We are required to build the application once the above steps are done before testing.
Enabling the Validator plug- in To enable the validator plug-in open the file struts-config.xml and make sure that following line is present in the file.

<!-- 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 Message resources are used by the Validator Framework to generate the validation error messages. In our application we need to define the messages for name, Address and E-mail address. Open the Struts\strutstutorial\web\WEB-INF\MessageResources.properties file and add the following lines: AddressForm.name=Name AddressForm.address=Address AddressForm.emailAddress=E-mail address Developing Validation rules In this application we are adding only one validation that the fields on the form should not be blank. Add the following code in the validation.xml.

<!-- 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 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 <arg key=".."/> tag. The value of key is taken from the message resources (Struts\strutstutorial\web\WEB-INF\MessageResources.properties). Applying Validation rules to JSP Now create the AddressJavascriptValidation.jsp file to test the application. The code for AddressJavascriptValidation.jsp is as follows:

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

<%@ taglib uri="/tags/struts-html" prefix="html" %> <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>

The code <html:javascript formName="AddressForm"/> 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.

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

Add the following line in the index.jsp to call the form. <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 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.

Client Side Address Validation in Struts Posted on: February 12, 2008 at 12:00 AM

In this lesson we will create JSP page for entering the address and use the functionality provided by Validator Framework to validate the user data on the browser.

Client Side Address Validation in Struts

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

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

<!-- 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 Message resources are used by the Validator Framework to generate the validation error messages. In our application we need to define the messages for name, Address and E-mail address. Open the Struts\strutstutorial\web\WEB-INF\MessageResources.properties file and add the following lines: AddressForm.name=Name AddressForm.address=Address AddressForm.emailAddress=E-mail address Developing Validation rules In this application we are adding only one validation that the fields on the form should not be blank. Add the following code in the validation.xml.

<!-- 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 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 <arg key=".."/> tag. The value of key is taken from the message resources (Struts\strutstutorial\web\WEB-INF\MessageResources.properties). Applying Validation rules to JSP Now create the AddressJavascriptValidation.jsp file to test the application. The code for AddressJavascriptValidation.jsp is as follows:

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <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>

The code <html:javascript formName="AddressForm"/> 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.

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

Add the following line in the index.jsp to call the form. <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 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.

Struts HTML Tags

Struts provides HTML tag library for easy creation of user interfaces. In this lesson I will show you what all Struts HTML Tags are available to the JSP for the development of user interfaces. To use the Struts HTML Tags we have to include the following line in our JSP file: <%@ taglib uri="/tags/struts-html" prefix="html" %> above code makes available the tag to the jsp.

Struts HTML Tags


<html:message key="thekey"/> 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

<html:password property="prop"

size="10"/> <html:text property="text1" size="5"/>

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.

<html:submit>Submit</html:submit> Tag creates a submit button with the provided content as the button text. <html:reset>Reset</html:reset> Tag creates a reset button with the provided content as the button text. Tag prints all the available error on the page. Tag creates the file upload element on the form. The property must be of the type org.apache.struts.upload.FormFile. Tag creates check box on the form.

<html:errors/> <html:file property="fileSelectionBox"/> <html:checkbox property="myCheckBox"/> <html:hidden property="hiddenfield"/> <html:radio value="abc" property="myCheckBox"/> <html:select multiple="true" property="selectBox">

Tag creates the hidden html element on the form.

Tag creates the check box on the form.

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

<html:textarea property="myTextArea" value="Hello Struts" /> <html:form action="/Address" method="post"> <html:base/>

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

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

Struts 1 > Struts Logic Tag

Struts Logic Tag


In this example you will learn how to use Struts Logic Tags. In order to use the Struts Logic Tag you need to include the following taglib directive in the jsp page.

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


To use the Struts Logic Tag Library you need to add the following <taglib> subelement to the web.xml file.

1.<jsp-config> 2.<taglib> 3.<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri> 4.<taglib-location>/WEB-INF/struts-logic.tld</taglib-location> 5.</taglib> 6.</jsp-config>


In this example we will create a user.jsp page wich displays the user details according to the conditions specified using the logic tags. The UserForm has the following attributes and the corresponding getter and setter methods.

1.private String name; 2.private int age; 3.private float height; 4.private float weight; 5.private String favouriteFood; 6.private ArrayList hobbies;
Initially we set default values for these attributes in the UserAction.

01.public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception { 02.ArrayList hobbiesList = new ArrayList(); 03.UserForm userForm = (UserForm)form; 04.userForm.setName("Eswar");

05.userForm.setAge(21); 06.userForm.setHeight(5.11f); 07.userForm.setWeight(70f); 08.userForm.setFavouriteFood("Fish and Chicken"); 09.hobbiesList.add("Music"); 10.hobbiesList.add("Art"); 11.hobbiesList.add("Dance"); 12.userForm.setHobbies(hobbiesList); 13.return mapping.findForward(SUCCESS); 14.}
Based on the conditions specified using the logic tags in the jsp page, the corresponding messages will be displayed to the user.

<logic:present /> <logic:notPresent />


The following code will dispaly "The User Name is Eswar." if the name attribute has some value else it will display "The User is not Present."

1.<logic:present name="UserForm" property="name"> 2.The User Name is Eswar. 3.</logic:present> 4.<logic:notPresent name="UserForm" property="name"> 5.The User is not Present. 6.</logic:notPresent>

<logic:equal /> <logic:notEqual />


The following code will dispaly "The age is equal to 18." if the value of the age attribute is 18 else it will dispaly "The age is not equal to 18."

1.<logic:equal name="UserForm" property="age" value="18"> 2.The age is equal to 18. 3.</logic:equal> 4.<logic:notEqual name="UserForm" property="age" value="18"> 5.The age is not equal to 18. 6.</logic:notEqual>

<logic:greaterEqual /> <logic:greaterThan />


The following code will dispaly "The height is greater than or equal to 5.11" if the value of the height attribute is equal to or greater than 5.11 else it will display "The height is greater than 5.11" if the value of the height attribute is greater than 5.11.

1.<logic:greaterEqual name="UserForm" property="height" value="5.11"> 2.The height is greater than or equal to 5.11 3.</logic:greaterEqual> 4.<logic:greaterThan name="UserForm" property="height" value="5.11"> 5.The height is greater than 5.11 6.</logic:greaterThan>

<logic:lessEqual /> <logic:lessThan />


The following code will dispaly "The weight is less than or equal to 70." if the value of the weight attribute is less than or equal to 70 else it will display "The weight is less than 70" if the value of the weight attribute is less than 70.

1.<logic:lessEqual name="UserForm" property="weight" value="70"> 2.The weight is less than or equal to 70. 3.</logic:lessEqual> 4.<logic:lessThan name="UserForm" property="weight" value="70"> 5.The weight is less than 70. 6.</logic:lessThan>

<logic:match /> <logic:notMatch />


The following code will display "The user's favourite food includes Chicken" if the value of the favouriteFood attribute contains "Chicken" else it will display "The user's favourite food does not include Chicken".

1.<logic:match name="UserForm" property="favouriteFood" value="Chicken"> 2.The user's favourite food includes Chicken. 3.</logic:match> 4.<logic:notMatch name="UserForm" property="favouriteFood" value="Chicken"> 5.The user's favourite food does not includes Chicken. 6.</logic:notMatch>

<logic:iterate />
The following code is used to iterate the ArrayList and display the contents.

1.<logic:iterate name="UserForm" property="hobbies" id="data"> 2.<bean:write name="data" /> 3.</logic:iterate>


On executing the example the following page will be displayed to the user.

You can download the source code of the Struts Logic Tag example by clicking on the Download link below.

Tag header
Define a scripting variable based on the value(s) of the specified request header. Retrieve the value of the specified request header (as a single value or multiple values, depending on the result as a page scope attribute of type

multiple attribute), and define the String (if multiple is not specified) or String[] (if multiple is specified).

If no header with the specified name can be located, and no default value is specified, a request time exception will be thrown.

Tag Information

Tag Class TagExtraInfo Class Body Content Display Name

org.apache.struts.taglib.bean.HeaderTag org.apache.struts.taglib.bean.HeaderTei empty None

Attributes
Name Required RequestType time false true
java.lang.String java.lang.String

Description
Specifies the name of the scripting variable (and associated page scope attribute) that will be made available with the value of the specified request header. If any arbitrary value for this attribute is specified, causes a call to HttpServletRequest.getHeaders() and a

id

true

multiple false

String[]. Otherwise, HttpServletRequest.getHeader() will be called, and a definition of the result as a bean of type String will be
definition of the result as a bean of type performed.

name value

true false

true true

java.lang.String java.lang.String

Specifies the name of the request header whose value, or values, is to be retrieved. The default header value to return if no header with the specified name was included in this request.

Variables
No Variables Defined.

bean

Tag define
Define a scripting variable based on the value(s) of the specified bean property. Create a new attribute (in the scope specified by the

toScope property, if any), and a corresponding scripting variable, both of which are named

by the value of the id attribute. The corresponding value to which this new attribute (and scripting variable) is set are specified via use of exactly one of the following approaches (trying to use more than one will result in a JspException being thrown):

Specify a name attribute (plus optional property and scope attributes) - The created attribute and scripting variable will be of the type of the retrieved JavaBean property, unless it is a Java primitive type, in which case it will be wrapped in the appropriate wrapper class (i.e. int is wrapped by java.lang.Integer). Specify a value attribute - The created attribute and scripting variable will be of type java.lang.String, set to the value of this attribute. Specify nested body content - The created attribute and scripting variable will be of type java.lang.String, set to the value of the nested body content.

If a problem occurs while retrieving the specified bean property, a request time exception will be thrown. The

<bean:define> tag differs from <jsp:useBean> in several ways, including:

Unconditionally creates (or replaces) a bean under the specified identifier. Can create a bean with the value returned by a property getter of a different bean (including properties referenced with a nested and/or indexed property name). Can create a bean whose contents is a literal string (or the result of a runtime expression) specified by the value attribute. Does not support nested content (such as <jsp:setProperty> tags) that are only executed if a bean was actually created.
id attribute more than once in a single <bean:define> for the same bean name more than once in a single page.

USAGE NOTE - There is a restriction in the JSP 1.1 Specification that disallows using the same value for an JSP page. Therefore, you will not be able to use

USAGE NOTE - If you use another tag to create the body content (e.g. bean:write), that tag must return a non-empty String. An empty String equates to an empty body or a null String, and a new scripting variable cannot be defined as null. Your bean must return a non-empty String, or the define tag must be wrapped within a logic tag to test for an empty or null value. USAGE NOTE - You cannot use bean:define to instantiate a DynaActionForm (type="org.apache.struts.action.DynaActionForm") with the properties specified in the struts-config. The mechanics of creating the dyna-properties is complex and cannot be handled by a no-argument constructor. If you need to create an ActionForm this way, you must use a conventional ActionForm. See the Bean Developer's Guide section on bean creation for more information about these differences, as well as alternative approaches to introducing beans into a JSP page.

Tag Information
Tag Class TagExtraInfo Class Body Content Display Name org.apache.struts.taglib.bean.DefineTag org.apache.struts.taglib.bean.DefineTei JSP None

Attributes
Name Required RequestType time false true
java.lang.String java.lang.String

Description
Specifies the name of the scripting variable (and associated page scope attribute) that will be made available with the value of the specified property. Specifies the attribute name of the bean whose property is accessed to define a new page scope attribute (if property is also specified) or the attribute name of the bean that is duplicated with the new reference created by this tag (if property is not also specified). This attribute is required unless you specify a nested body content.

id name

true false

value attribute or

property false

true

java.lang.String

Specifies the name of the property to be accessed on the bean specified by name. This value may be a simple, indexed, or nested property reference expression. If not specified, the bean identified by given a new reference identified by

name is

id.

scope

false

true true true true

java.lang.String

Specifies the variable scope searched to retrieve the bean specified by name. If not specified, the default rules applied by

PageContext.findAttribute() are applied.

toScope false type value false false

java.lang.String java.lang.String java.lang.String

Specifies the variable scope into which the newly defined bean will be created. If not specified, the bean will be created in page scope. Specifies the fully qualified class name of the value to be exposed as the id attribute. The

should be set. This attribute is required unless you specify the attribute or nested body content.

java.lang.String value to which the exposed bean name

Variables
No Variables Defined.

bean

Tag cookie
Define a scripting variable based on the value(s) of the specified request cookie. Retrieve the value of the specified request cookie (as a single value or multiple values, depending on the result as a page scope attribute of type

multiple attribute), and define the Cookie (if multiple is not specified) or Cookie[] (if multiple is specified).

If no cookie with the specified name can be located, and no default value is specified, a request time exception will be thrown.

Tag Information
Tag Class TagExtraInfo Class Body Content Display Name org.apache.struts.taglib.bean.CookieTag org.apache.struts.taglib.bean.CookieTei empty None

Attributes
Name Required RequestType time false true
java.lang.String java.lang.String

Description
Specifies the name of the scripting variable (and associated page scope attribute) that will be made available with the value of the specified request cookie. If any arbitrary value for this attribute is specified, causes all matching cookies to be accumulated and stored into a bean of type Cookie[]. If not specified, the first value for the specified cookie will be retrieved as a value of type

id

true

multiple false

Cookie.

name value

true false

true true

java.lang.String java.lang.String

Specifies the name of the request cookie whose value, or values, is to be retrieved. The default cookie value to return if no cookie with the specified name was included in this request.

Variables
No Variables Defined.

bean

Tag include
Load the response from a dynamic application request and make it available as a bean. Perform an internal dispatch to the specified application component (or external URL) and make the response data from that request available as a bean of type String. This tag has a function similar to that of the standard <jsp:include> tag, except that the response data is stored in a page scope attribute instead of being written to the output stream. If the current request is part of a session, the generated request for the include will also include the session identifier (and thus be part of the same session). The URL used to access the specified application component is calculated based on which of the following attributes you specify (you must specify exactly one of them):

forward - Use the value of this attribute as the name of a global ActionForward to be looked up, and use the module-relative or context-relative URI found there. href - Use the value of this attribute unchanged (since this might link to a resource external to the application, the session identifier is not included. page - Use the value of this attribute as an module-relative URI to the desired resource.

Tag Information
Tag Class TagExtraInfo Class Body Content Display Name org.apache.struts.taglib.bean.IncludeTag org.apache.struts.taglib.bean.IncludeTei empty None

Attributes
Name Required RequestType time true true
java.lang.String java.lang.String

Description
Optional anchor tag ("#xxx") to be added to the generated hyperlink. Specify this value without any "#" character. Logical name of a global ActionForward that contains the actual content-relative URI of the resource to be included.

anchor forward

false false

href

false

true

java.lang.String

Absolute URL (including the appropriate protocol prefix such as "http:") of the resource to be included. Because this URL could be external to the current web application, the session identifier will not be included in the request. Specifies the name of the scripting variable (and associated page scope attribute) that will be made available with the value of the specified web application resource. Module-relative URI (starting with a '/') of the web application resource to be included. Set to true if you want the current transaction control token included in the generated URL for this include.

id page

true false

false true true

java.lang.String java.lang.String boolean

transaction false

Variables
No Variables Defined.

Struts Logic Tags

Struts Logic Tags examples.

1. Introduction to Struts Logic Tags Struts logic tags are conditional tags that replaces scriptlets in the jsp files. 2. Logic Empty and notEmpty Tags Tag evaluation of the nested body content occurs only if the specified value is either absent (i.e. null), an empty string (i.e. a java.lang.String with a length of zero) 3. Logic Equal and notEqual Tags if the requested variable is equal to the specified value then this tag is used to evaluate the contents contained in the nested body parts of this tag 4. Logic greaterEqual and greaterThan Tags This tag compares the variable against the specified constant value. If the variable is greater than or equal to the specified value then the nested body contents of this tag is evaluated

5. Logic lessEqual and lessThan Tags This tag compares the variable against the specified constant value. If the variable is less than or equal to the specified value then the nested body contents of this tag is evaluated 6. Logic match and notMatch Tags This tag matches the variable specified as a String against the specified constant value. If the value is a substring then the nested body content of this tag is evaluated. 7. Logic present and notPresent Tags This tag checks the current request and depending on which attribute is specified, it evaluates the nested body content of this tag only if the specified value is present.

8. Logic Present Tag (<logic:equal>...</logic:equal>) Logic Present Tag

Struts Logic Tags: An Introduction

Struts logic tags are conditional tags that replaces scriptlets in the jsp files.

This tag library contains tags that do the following things : conditional generation of the output text, generate iterations to output the text, application flow management, matching strings and substrings...

Logic tags available in the Struts Framework

Tag Name empty

Description
If the requested variable is either null or an empty string then the nested body content of this tag is evaluated

equal

If the requested variable is equal to the specified value then the nested body content of this tag is evaluated It forwards the control to the page specified by the specified ActionForward entry. If the value of the requested variable is greater than or equal to the specified value then the nested body content of this tag is evaluated If the value of the requested variable is greater than the specified value then the nested body content of this tag is evaluated It repeats the nested body content of this tag over a specified collection. If the value of the requested variable is less than or equal to the specified value then the nested body content of this tag is evaluated If the value of the requested variable is less than the specified value then the nested body content of this tag is evaluated Evaluates the nested body content of this tag if the specified value is an appropriate substring of the requested variable.

forward

greaterEqual

greaterThan

iterate

lessEqual

lessThan

match

If the specified message is not present in messagesNotPresent the request then it generates the nested body content of this tag .

messagesPresent

If the specified message is present in this request then it generates the nested

body content of this tag . If the requested variable is neither null nor an empty string nor an empty java.util.Collection (tested by the isEmpty() method on the java.util.Collection interface) then the nested body content of this tag is evaluated If the requested variable is not equal to the specified value then the nested body content of this tag is evaluated If the specified value is not an appropriate substring of the requested variable then the nested body content of this tag is evaluated If the specified value is not present in the request then it generates the nested body content of this tag . If the specified value is present in the request then it generates the nested body content of this tag It renders an HTTP Redirect request.

notEmpty

notEqual

notMatch

notPresent

present redirect

Struts logic tags uses equal, greaterEqual, greaterThan, lessEqual, lessThan, notEqual tags to compare the values. There are rules that must be followed :

Initially the specified variable needed to be compared is examined (whether it can be converted to a double or to a long). Then a numeric (either floating point or integer) type comparison is done. If numeric conversion fails than a String comparison is performed. The variable to be compared is retrieved from the request attribute(s) that may be a cookie, header, name, parameter or property available to the specified tag. This variable is then converted to the appropriate type needed for the comparison.. If the variable or property to be compared returns null, it is converted into a zero-length string before the comparison occurs. If the comparison logic returns a true value then only the specific comparison is performed and subsequently the nested body content is evaluated .

Struts logic tags can also do the substring matching using the tags (match, notMatch). There are rules that must be followed :

The variable to be compared is retrieved from the request attribute(s) that may be a cookie, header, name, parameter or property available on this tag. Then this variable is converted to a String, if necessary. If the retrieval of the variable fails or it contains a null value then a request time exception is thrown. The existence of the variable as a substring is examined at the position specified by the location attribute Location can be specified at the beginning (if location is set to start), at the end (if location is set to end), or anywhere (if location is not specified).

actual exception that caused the problem, a request attribute under key to the error page. In the subsequent section we will show you the examples of these tags.

JspException is thrown at runtime if any tag is utilized incorrectly or any invalid combination of tag attributes are used. To process the org.apache.struts.action.EXCEPTION is passed

Logic Empty Tag (...) Posted on: June 2, 2007 at 12:00 AM Empty tag - If the requested variable is either null or an empty string then we use this tag to evaluate the contents contained in the nested body parts of this tag.

Logic Empty Tag (<logic:empty>...</logic:empty>)

empty tag - If the requested variable is either null or an empty string then we use this tag to evaluate the contents

contained in the nested body parts of this tag.

null), an empty string (i.e. a java.lang.String with a length of zero), or an empty java.util.Collection or java.util.Map (tested by the
Tag evaluation of the nested body content occurs only if the specified value is either absent (i.e. isEmpty() method on the respective interface). Attributes of Empty Tag

Attribute Name name property scope

Description
This attribute specifies a JSP bean variable which is required to make comparison. The variable contains the property of the bean which is required to make comparison and is specified by the name attribute. This specifies the bean scope within which the bean is searched by the name property, or "any scope" if not specified.

Logic notEmpty Tag (<logic:notEmpty>...</logic:notEmpty>)


notEmpty - If the requested variable is neither null nor an empty string then we use this tag to evaluate the

contents contained in the nested body parts of this tag.

Tag evaluation of the nested body content occurs only if the specified value is available (i.e.not

null) and is not an empty string (i.e. a

java.lang.String with a length of zero).


Attributes of notEmpty Tag

Attribute Name name property scope

Description
This attribute specifies a JSP bean variable which is required to make comparison. The variable contains the property of the bean which is required to make comparison and is specified by the name attribute. This specifies the bean scope within which the bean is searched by the name property, or "any scope" if not specified.

Example Illustrating the use of the Empty<logic:empty> and the notEmpty <logic:notEmpty> logic tags.
Here you will learn to use the Struts Logic tags. We will cover an example that will show a comparison between the two logic tags (ie..<logic:empty> and the <logic:notEmpty>). Example code Creating an Action Class Develop a simple action class

EmptyAction.java.

package roseindia.net; import java.io.*; import java.util.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import import import import javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.ServletException; org.apache.struts.action.*;

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

throws IOException, ServletException {

return mapping.findForward("success"); } }
Creating Form Bean Our form bean class contains only one property text. Here is the code of FormBean (EmptyForm.java)

package roseindia.net; import org.apache.struts.action.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EmptyForm extends ActionForm { private String text = ""; public String getText() { return text; } public void setText(String text) { this.text=text; }

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

<form-bean name="EmptyForm"

type="roseindia.net.EmptyForm"/>

Developing the Action Mapping in the struts-config.xml Here, Action mapping helps to select the method from the Action class for specific requests.

<action path="/EmptyAction" type="roseindia.net.EmptyAction" name="EmptyForm" scope="request" input="/pages/input.jsp"> <forward name="success" path="/pages/output.jsp"/> </action>

Developing the input.jsp page

<%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html> <head> <title>Using &lt;logic&gt; Tags</title> </head> <body> <h1>Using &lt;logic&gt; Tags</h1> <html:form action="/EmptyAction" method ="post"> <h2>Enter your name:</h2> <html:text property="text"/> <br> <br> <html:submit value="Submit"/>

<html:cancel/> </html:form> </body> </html:html>

Developing the output.jsp page

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <HTML> <HEAD> <TITLE>Here's Your Data...</TITLE> </HEAD> <BODY> <H3>Here's Your Data...</H3> <h4>The text field text:</h4> <bean:write name="EmptyForm" property="text"/> <logic:notEmpty name="EmptyForm" property="text" scope="request"> <h4>Using the tag &lt;logic:notEmpty &gt; </h4> Results:not Empty </logic:notEmpty>

<logic:empty name="EmptyForm" property="text" scope="request"> <h4>Using the tag&lt;logic:empty &gt;</h4> Results: Empty </logic:empty> </BODY> </HTML>

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

<li> <html:link page="/pages/input.jsp">Struts File Upload</html:link> <br> Example demonstrates how EmptyAction Class works. </li> Building and Testing the Example To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the input.jsp page. Your browser displays the following page. Writing nothing to the out.jsp page displays the working of the Empty Logic tag <logic:empty >

Writing nothing displays the following out.jsp page

Now write any data to the input.jsp to see the working of the notEmpty logic tag <logic:notEmpty >

The <logic:notEmpty > evaluated here displays the output.jsp as

Logic Equal Tag (...) Posted on: June 2, 2007 at 12:00 AM Equal tag - if the requested variable is equal to the specified value then this tag is used to evaluate the contents contained in the nested body parts of this tag.

Logic Equal Tag (<logic:equal>...</logic:equal>)

equal tag - if the requested variable is equal to the specified value then this tag is used to evaluate the contents

contained in the nested body parts of this tag.

Compares the variable passed against the specified constant value. The nested body content of this tag is evaluated if the variable and value are equal.

Attribute Name cookie header

Description
The variable contains the cookie value needed to compare .Here the name is specified by this attribute. The variable contains the header value needed to compare whose name is specified by this attribute. The name match is performed in a case insensitive manner.

Attribute Name name parameter property scope value

Description
The variable to be compared is the JSP bean specified by this attribute, if property is not specified, or the value of the specified property of this bean, if

property is specified.

The variable to be compared is the first, or only, value of the request parameter specified by this attribute. The variable contains the bean property value needed to compare ,it is specified by this attribute. The property reference can be simple, nested, and/or indexed. This specifies the bean scope within which the bean is searched by the name property, or "any scope" if not specified. The constant value is specified by other attribute(s) of this tag, needed to compare

Logic notEqual Tag (<logic:notEqual >...</logic:notEqual>)


notEmpty - if the requested variable is not equal to the specified value then this tag is used to evaluate the contents

contained in the nested body parts of this tag.

Compares the variable passed against the specified constant value. The nested body content of this tag is evaluated if the variable and value are not equal. Attributes of notEmpty Tag

Attribute Name cookie header name parameter property scope value

Description
The variable contains the cookie value needed to compare .Here the name is specified by this attribute. The variable contains the header value needed to compare whose name is specified by this attribute. The name match is performed in a case insensitive manner. The variable to be compared is the JSP bean specified by this attribute, if property is not specified, or the value of the specified property of this bean, if property is specified. The variable to be compared is the first, or only, value of the request parameter specified by this attribute. The variable contains the bean property value needed to compare ,it is specified by this attribute. The property reference can be simple, nested, and/or indexed. This specifies the bean scope within which the bean is searched by the name property, or "any scope" if not specified. The constant value is specified by other attribute(s) of this tag, needed to compare

Example Illustrating the use of the Equal<logic:equal> and the notEqual <logic:notEqual> logic tags.
Here you will learn to use the Struts Logic Equal and notEqual tags. We will cover an example that will show a comparison between the two logic tags (ie..<logic:equal > and the <logic:notEqual >).

Example code Creating an Action Class Develop a simple action class

LogicAction.java.

package roseindia.net; import java.io.*; import java.util.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import import import import javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.ServletException; org.apache.struts.action.*;

public class LogicAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

return mapping.findForward("success"); } }
Creating Form Bean Our form bean class contains only one property number. Here is the code of FormBean (LogicForm.java)

package roseindia.net; import org.apache.struts.action.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net

**/ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LogicForm extends ActionForm { private long number; public long getNumber() { return number; } public void setNumber(long number) { this.number=number; }

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

<form-bean name="LogicForm" type="roseindia.net.LogicForm" />

Developing the Action Mapping in the struts-config.xml Here, Action mapping helps to select the method from the Action class for specific requests.

<action path="/LogicAction" type="roseindia.net.LogicAction" name="LogicForm" scope="request" input="/pages/InputLogic.jsp"> <forward name="success" path="/pages/output.jsp"/> </action>

Developing the InputLogic.jsp page

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

<%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html> <head> <title>Using &lt;logic&gt; Tags</title> </head> <body> <h1>Using &lt;logic&gt; Tags</h1> <html:form action="/LogicAction" method ="post"> <h2>Enter a number:</h2> <html:text property="number"/> <br> <h3>The &lt;logic:Equal&gt;tag works if you enter 1</h3> <h3>else The &lt;logic:notEqual&gt; is processed </h3> <br> <html:submit value="Submit"/>

<html:cancel/> </html:form> </body> </html:html>

Developing the output.jsp page

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

<HTML> <HEAD> <TITLE>Here's Your Data...</TITLE> </HEAD> <BODY> <H3>Here's Your Data...</H3> <h4>The number entered is: <bean:write name="LogicForm" property="number"/></h4> <logic:equal name="LogicForm" property="number" value="1"> <h4>Using the tag &lt;logic:equal &gt;</h4> Result : Equal </logic:equal> <logic:notEqual name="LogicForm" property="number" value="1"> <h4>Using the tag &lt;logic:notEqual &gt; </h4> Result : notEqual </logic:notEqual>

</BODY> </HTML>
Add the following line in the index.jsp to call the form. <li> <html:link page="/pages/InputLogic.jsp">Struts File Upload</html:link> <br> Example demonstrates how LogicAction Class works. </li> Building and Testing the Example To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the InputLogic.jsp page. Your browser displays the following page. Writing value equal to1 to the InputLogic.jsp page displays the working of the Equal Logic tag <logic:equal >

It displays the following out.jsp page

Now write any data other than 1 to the InputLogic.jsp to see the working of the notEqual logic tag <logic:notEqual>

The <logic:notEqual > evaluated here displays the output.jsp as

Logic greaterEqual Tag (... ) Posted on: June 2, 2007 at 12:00 AM Empty tag -if the requested variable is greater than or equal to the specified value then this tag is used to evaluate the contents contained in the nested body parts of this tag.

Logic greaterEqual Tag (<logic: greaterEqual>...</logic:greaterThan>)

empty tag - if the requested variable is greater than or equal to the specified value then this tag is used to evaluate

the contents contained in the nested body parts of this tag.

This tag compares the variable against the specified constant value. If the variable is greater than or equal to the specified value then the nested body contents of this tag is evaluated Attributes of greaterEqual Tag

Attribute Name cookie header name parameter property scope value

Description
The variable contains the cookie value needed to compare .Here the name is specified by this attribute. The variable contains the header value needed to compare whose name is specified by this attribute. The name match is performed in a case insensitive manner. The variable to be compared is the JSP bean specified by this attribute, if not specified, or the value of the specified property of this bean, if

property is property is specified.

The variable to be compared is the first, or only, value of the request parameter specified by this attribute. The variable contains the bean property value needed to compare ,it is specified by this attribute. The property reference can be simple, nested, and/or indexed. This specifies the bean scope within which the bean is searched by the "any scope" if not specified.

name property, or

The constant value is specified by other attribute(s) of this tag, needed to compare

Logic greaterThan Tag (<logic: greaterThan>... </ logic:greaterThan>)


greaterThan Tag : Tag evaluation of the nested body content occurs only if the specified value is greater than the

specified value.

This tag compares the variable against the specified constant value. If the variable is greater than the specified value then the nested body contents of this tag is evaluated Attributes of greaterThan Tag

Attribute Name cookie header name parameter property scope value

Description
The variable contains the cookie value needed to compare .Here the name is specified by this attribute. The variable contains the header value needed to compare whose name is specified by this attribute. The name match is performed in a case insensitive manner. The variable to be compared is the JSP bean specified by this attribute, if property is not specified, or the value of the specified property of this bean, if

property is specified.
The variable to be compared is the first, or only, value of the request parameter specified by this attribute. The variable contains the bean property value needed to compare ,it is specified by this attribute. The property reference can be simple, nested, and/or indexed. This specifies the bean scope within which the bean is searched by the property, or "any scope" if not specified.

name

The constant value is specified by other attribute(s) of this tag, needed to compare

Example Illustrating the use of the Logic greaterEqual Tag<logic:greaterEqual> and the Logic greaterThan Tag<logic:greaterThan> .
Here you will learn to use the Struts Logic tags. We will cover an example that will show a comparison between the two logic tags (ie..<;logic:greaterEqual> and the <logic:greaterThan>). Example code Creating an Action Class Develop a simple action class

LogicAction.java.

package roseindia.net; import java.io.*; import java.util.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import import import import javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.ServletException; org.apache.struts.action.*;

public class LogicAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

return mapping.findForward("success"); } }
Creating Form Bean Our form bean class contains only one property number. Here is the code of FormBean (LogicForm.java)

package roseindia.net; import org.apache.struts.action.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LogicForm extends ActionForm { private long number; public long getNumber() { return number; } public void setNumber(long number) { this.number=number; }

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

<form-bean name="LogicForm" type="roseindia.net.LogicForm" />

Developing the Action Mapping in the struts-config.xml Here, Action mapping helps to select the method from the Action class for specific requests.

<action path="/LogicAction" type="roseindia.net.LogicAction" name="LogicForm" scope="request" input="/pages/InputLogic.jsp"> <forward name="success" path="/pages/output.jsp"/> </action>

Developing the InputLogic.jsp page

<%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html> <head> <title>Using &lt;logic&gt; Tags</title> </head> <body> <h1>Using &lt;logic&gt; Tags</h1> <html:form action="/LogicAction" method ="post"> <h2>Enter a number:</h2> <html:text property="number"/> <br> <h3>The &lt;logic:greaterEqual&gt;tag works if you enter a value</h3> <h3>greater than or equal to 1</h3> <h3>The &lt;logic:greaterThan&gt;tag

works if you enter a value</h3> <h3>greater than to 10000</h3> <br> <html:submit value="Submit"/>

<html:cancel/> </html:form> </body> </html:html>

Developing the output.jsp page

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <HTML> <HEAD> <TITLE>Here's Your Data...</TITLE> </HEAD> <BODY> <H3>Here's Your Data...</H3> <h4>The number entered is: <bean:write name="LogicForm" property="number"/></h4>

<logic:greaterEqual name="LogicForm" property="number" value="1"> <h4>Using the tag&lt;logic:greaterEqual&gt;</h4> Result : greaterEqual </logic:greaterEqual>

<logic:greaterThan name="LogicForm" property="number" value="10000"> <h4>Using the tag &lt;logic:greaterThan &gt; </h4> Result : greaterThan </logic:greaterThan>

</BODY> </HTML>
Add the following line in the index.jsp to call the form. <li> <html:link page="/pages/InputLogic.jsp">Struts File Upload</html:link> <br> Example demonstrates how LogicAction Class works. </li> Building and Testing the Example To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the InputLogic.jsp page. Your browser displays the following page. Entering a number greater than 1 and less than 10000 to the InputLogic.jsp page evaluates the working of the <logic:greaterEqual> tag

It displays the following out.jsp page

Writing a number greater than 10000 to the InputLogic.jsp displays

The output.jsp displays the working of the both tags.

Logic LessEqual Tag (...) Posted on: June 2, 2007 at 12:00 AM LessEqual Tag - If the requested variable is either less or equal to the specified values then we use this tag to evaluate the contents contained in the nested body parts of this tag.

Logic LessEqual Tag (<logic:lessEqual>...</logic:lessEqual>)

lessEqual Tag - If the requested variable is either less or equal to the specified values then we use this tag to

evaluate the contents contained in the nested body parts of this tag.

This tag compares the variable against the specified constant value. If the variable is less than or equal to the specified value then the nested body contents of this tag is evaluated Attributes of lessEqual Tag

Attribute Name cookie header

Description
The variable contains the cookie value needed to compare .Here the name is specified by this attribute. The variable contains the header value needed to compare whose name is specified by this attribute. The name match is performed in a case insensitive manner.

name parameter property scope value

The variable to be compared is the JSP bean specified by this attribute, if property is not specified, or the value of the specified property of this bean, if

property is specified.
The variable to be compared is the first, or only, value of the request parameter specified by this attribute. The variable contains the bean property value needed to compare ,it is specified by this attribute. The property reference can be simple, nested, and/or indexed. This specifies the bean scope within which the bean is searched by the property, or "any scope" if not specified.

name

The constant value is specified by other attribute(s) of this tag, needed to compare

Logic LessThan Tag (<logic:lessThan >...</logic:lessThan>)


lessThan Tag- If the requested variable is less than the specified values then we use this tag to evaluate the

contents contained in the nested body parts of this tag.

This tag compares the variable against the specified constant value. If the variable is less than the specified value then the nested body contents of this tag is evaluated Attributes of lessThan Tag

Attribute Name cookie header name parameter property scope value

Description
The variable contains the cookie value needed to compare .Here the name is specified by this attribute. The variable contains the header value needed to compare whose name is specified by this attribute. The name match is performed in a case insensitive manner. The variable to be compared is the JSP bean specified by this attribute, if not specified, or the value of the specified property of this bean, if specified.

property is property is

The variable to be compared is the first, or only, value of the request parameter specified by this attribute. The variable contains the bean property value needed to compare ,it is specified by this attribute. The property reference can be simple, nested, and/or indexed. This specifies the bean scope within which the bean is searched by the or "any scope" if not specified.

name property,

The constant value is specified by other attribute(s) of this tag, needed to compare

Example Illustrating the use of the lessEqual <logic:LessEqual > and the lessThan <logic:LessThan > logic tags.
Here you will learn to use the Struts Logic tags. We will cover an example that will show a comparison between the two logic tags (ie..<logic:lessEqual > and the <logic:LessThan >). Example code Creating an Action Class Develop a simple action class

LogicAction.java.

package roseindia.net; import java.io.*; import java.util.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import import import import javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.ServletException; org.apache.struts.action.*;

public class LogicAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

return mapping.findForward("success"); } }
Creating Form Bean Our form bean class contains only one property number. Here is the code of FormBean (LogicForm.java)

package roseindia.net;

import org.apache.struts.action.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LogicForm extends ActionForm { private long number; public long getNumber() { return number; } public void setNumber(long number) { this.number=number; }

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

<form-bean name="LogicForm" type="roseindia.net.LogicForm" />

Developing the Action Mapping in the struts-config.xml Here, Action mapping helps to select the method from the Action class for specific requests.

<action path="/LogicAction" type="roseindia.net.LogicAction" name="LogicForm" scope="request" input="/pages/InputLogic.jsp"> <forward name="success" path="/pages/output.jsp"/>

</action>

Developing the InputLogic.jsp page

<%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html> <head> <title>Using &lt;logic&gt; Tags</title> </head> <body> <h1>Using &lt;logic&gt; Tags</h1> <html:form action="/LogicAction" method ="post"> <h2>Enter a number:</h2> <html:text property="number"/> <br> <h3>The &lt;logic:lessEqual&gt;tag works if you enter a value</h3> <h3>less than or equal to 100</h3> <h3>The &lt;logic:lessThan&gt;tag works if you enter a value</h3> <h3>less than to 10000</h3> <br> <html:submit value="Submit"/>

<html:cancel/> </html:form> </body> </html:html>

Developing the output.jsp page

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <HTML> <HEAD> <TITLE>Here's Your Data...</TITLE> </HEAD> <BODY> <H3>Here's Your Data...</H3> <h4>The number entered is: <bean:write name="LogicForm" property="number"/></h4>

<logic:lessEqual name="LogicForm" property="number" value="100"> <h4>Using the tag&lt;logic:lessEqual&gt;</h4> Result : lessEqual </logic:lessEqual>

<logic:lessThan name="LogicForm" property="number" value="10000"> <h4>Using the tag &lt;logic:lessThan &gt; </h4> Result : lessThan </logic:lessThan>

</BODY> </HTML></HTML>
Add the following line in the index.jsp to call the form. <li> <html:link page="/pages/InputLogic.jsp">Struts File Upload</html:link> <br> Example demonstrates how LogicAction Class works. </li>

Building and Testing the Example To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the InputLogic.jsp page. Your browser displays the following page. Writing a number equal to 101 to the InputLogic.jsp page displays the working of the lessThan Logic tag <logic:lessThan >

It displays the following out.jsp page

Now write data equal 100 to the InputLogic.jsp to compare the working of the lessEqual and lessThan tags

Here both tags are evaluated it displays the output.jsp as

Logic Match Tag (...) Posted on: June 2, 2007 at 12:00 AM Match tag - We use this tag to evaluate the contents contained in the nested body parts of this tag if the specified value is an appropriate substring of the requested variable.

Logic Match Tag (<logic:match >...</logic:match >)

match tag - We use this tag to evaluate the contents contained in the nested body parts of this tag if the specified

value is an appropriate substring of the requested variable.

This tag matches the variable specified as a String against the specified constant value. If the value is a substring then the nested body content of this tag is evaluated. Attributes of match Tag

Attribute Name cookie header

Description
The variable to be matched is the value of the cookie whose name is specified by this attribute. The variable to be matched is the value of the header whose name is specified by this attribute. The name match is performed in a case insensitive manner.

Attribute Name location name parameter property scope value

Description
If not specified, a match between the variable and the value may occur at any position within the variable string. If specified, the match must occur at the specified location (either start or end) of the variable string. The variable to be matched is the JSP bean specified by this attribute, if property is not specified, or the value of the specified property of this bean, if

property is specified.
The variable to be matched is the first, or only, value of the request parameter specified by this attribute. The variable to be matched is the property (of the bean specified by the name attribute) specified by this attribute. The property reference can be simple, nested, and/or indexed. The bean scope within which to search for the bean named by the or "any scope" if not specified.

name property,

The constant value which is checked for existence as a substring of the specified variable.

Logic notMatch Tag (<logic:notMatch >...</logic:notMatch >)


notMatch - We use this tag to evaluate the contents contained in the nested body parts of this tag if the specified

value is not a substring of the requested variable.

This tag matches the variable specified by one of attributes (as a String) against the specified constant value. If the value is not a substring the nested body content of this tag is evaluated.

Attributes of notMatch Tag

Attribute Name cookie header location name parameter property scope

Description
The variable to be matched is the value of the cookie whose name is specified by this attribute. The variable to be matched is the value of the header whose name is specified by this attribute. The name match is performed in a case insensitive manner. If not specified, a match between the variable and the value may occur at any position within the variable string. If specified, the match must occur at the specified location (either start or end) of the variable string. The variable to be matched is the JSP bean specified by this attribute, if not specified, or the value of the specified property of this bean, if specified.

property is property is

The variable to be matched is the first, or only, value of the request parameter specified by this attribute. The variable to be matched is the property (of the bean specified by the name attribute) specified by this attribute. The property reference can be simple, nested, and/or indexed. The bean scope within which to search for the bean named by the "any scope" if not specified.

name property, or

Attribute Name value

Description

The constant value which is checked for existence as a substring of the specified variable.

Example Illustrating the use of the Match <logic:match > and the notMatch <logic:notMatch > logic tags.
Here you will learn to use the Struts Logic tags. We will cover an example that will show a comparison between the two logic tags (ie..<logic:match > and the <logic:notMatch>). Example code Creating an Action Class Develop a simple action class

LogicAction.java.

package roseindia.net; import java.io.*; import java.util.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import import import import javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.ServletException; org.apache.struts.action.*;

public class LogicAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

return mapping.findForward("success"); } }
Creating Form Bean

Our form bean class contains only one property text. Here is the code of FormBean (LogicForm.java)

package roseindia.net; import org.apache.struts.action.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EmptyForm extends ActionForm { private String text = ""; public String getText() { return text; } public void setText(String text) { this.text=text; }

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

<form-bean name="LogicForm" type="roseindia.net.LogicForm" />

Developing the Action Mapping in the struts-config.xml Here, Action mapping helps to select the method from the Action class for specific requests.

<action path="/LogicAction" type="roseindia.net.LogicAction" name="LogicForm"

scope="request" input="/pages/InputLogic.jsp"> <forward name="success" path="/pages/output.jsp"/> </action>

Developing the InputLogic.jsp page

<%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html> <head> <title>Using &lt;logic&gt; Tags</title> </head> <body> <h1>Using &lt;logic&gt; Tags</h1> <html:form action="/LogicAction" method ="post"> <h2>Enter text:</h2> <html:text property="text"/> <br> <h4>The &lt;logic:match&gt;tag works if the entered </h4> <h4>text contains "amit"</h4> <h4>The &lt;logic:notMatch&gt;tag always evaluate the </h4> <h4>entered text against the"abc" value</h4> <br> <html:submit value="Submit"/>

<html:cancel/>

</html:form> </body> </html:html>

Developing the output.jsp page Notice the values

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <HTML> <HEAD> <TITLE>Here's Your Data...</TITLE> </HEAD> <BODY> <H4>Here's Your Data...</H4> <h4>The text entered is: <bean:write name="LogicForm" property="text"/></h4>

<logic:match name="LogicForm" property="text" value="amit"> <h5>Using the tag &lt;logic:match &gt; </h5> Result : entered text contains "amit" </logic:match>

<logic:notMatch name="LogicForm" property="text" value="abc"> <h5>Using the tag&lt;logic:notMatch&gt;</h5> Result: entered text does not contains "abc" </logic:notMatch> </BODY>

</HTML>

Add the following line in the index.jsp to call the form. <li> <html:link page="/pages/InputLogic.jsp">Struts File Upload</html:link> <br> Example demonstrates how LogicAction Class works. </li> Building and Testing the Example To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the InputLogic.jsp page. Your browser displays the following page. Writing text including "amit" and excluding "abc" to the InputLogic.jsp page displays the working of the match Logic tag <logic:match > and the notMatch Logic tag <logic:notMatch > .

It displays the following to the out.jsp page

Writing text including "amit" and "abc" to the InputLogic.jsp page displays the working of the match Logic tag <logic:match > and the notMatch Logic tag <logic:notMatch > .

The <logic:notEqual > evaluated here displays the output.jsp as

Logic Present Tag (...) Posted on: June 2, 2007 at 12:00 AM Present tag -This tag evaluates its nested body contents if the specified value is present in the request.

Logic Present Tag (<logic:present >...</logic:present >)

present tag -This tag evaluates its nested body contents if the

specified value is present in the request.

This tag checks the current request and depending on which attribute is specified, it evaluates the nested body content of this tag only if the specified value is present. Attributes of Present Tag

Attribute Name cookie header name parameter

Description

It checks the existence of a cookie with the specified name. It checks the existence of an HTTP header with the specified name. The name match is performed in a case insensitive manner. It checks the existence of a JSP bean, in any scope, with the specified name. If property is also specified, checks for a non-null property value for the specified property. It checks the existence of at least one occurrence of the specified request parameter on this request, even if the parameter value is a zero-length string.

Attribute Name property role scope user

Description
It checks the existence of a non-null property value, returned by a property getter method on the JSP bean (in any scope) that is specified by the name attribute. Property references can be simple, nested, and/or indexed. It checks whether the currently authenticated user (if any) has been associated with any of the specified security roles. Use a commadelimited list to check for multiple roles. The bean scope within which to search for the bean named by the name property, or "any scope" if not specified. It checks whether the currently authenticated user principal has the specified name.

Logic notPresent Tag (<logic:not Present>...</logic:not Present>)


notPresent tag -This tag evaluates its nested body content if the specified value is not present in the request.
Tag evaluation of the nested body content occurs only if the specified value is not available in the request i.e... works in reverses to present tag. Attributes of notPresent Tag

Attribute Name cookie header name parameter property role scope user

Description

It checks the existence of a cookie with the specified name. It checks the existence of an HTTP header with the specified name. The name match is performed in a case insensitive manner. It checks the existence of a JSP bean, in any scope, with the specified name. If property is also specified, checks for a non-null property value for the specified property. It checks the existence of at least one occurrence of the specified request parameter on this request, even if the parameter value is a zero-length string. It checks the existence of a non-null property value, returned by a property getter method on the JSP bean (in any scope) that is specified by the name attribute. Property references can be simple, nested, and/or indexed. It checks whether the currently authenticated user (if any) has been associated with the specified security role. The bean scope within which to search for the bean named by the property, or "any scope" if not specified.

name

It checks whether the currently authenticated user principal has the specified name.

Example Illustrating the use of the present <logic:present > and the notPresent <logic:notPresent > logic tags.
Here you will learn to use the Struts Logic tags. We will cover an example that will show a comparison between the two logic tags (ie..<logic:present > and the <logic:notPresent >). Example code Creating an Action Class Develop a simple action class

LogicAction.java.

package roseindia.net; import java.io.*; import java.util.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import import import import javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.ServletException; org.apache.struts.action.*;

public class LogicAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

return mapping.findForward("success"); } }
Creating Form Bean Our form bean class contains only one property text. Here is the code of FormBean (LogicForm.java)

package roseindia.net; import org.apache.struts.action.*;

/** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net **/ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EmptyForm extends ActionForm { private String text = ""; public String getText() { return text; } public void setText(String text) { this.text=text; }

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

<form-bean name="LogicForm" type="roseindia.net.LogicForm" />

Developing the Action Mapping in the struts-config.xml Here, Action mapping helps to select the method from the Action class for specific requests.

<action path="/LogicAction" type="roseindia.net.LogicAction" name="LogicForm" scope="request" input="/pages/InputLogic.jsp"> <forward name="success" path="/pages/output.jsp"/>

</action>

Developing the InputLogic.jsp page

<%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <html:html> <head> <title>Using &lt;logic&gt; Tags</title> </head> <body> <h1>Using &lt;logic&gt; Tags</h1> <html:form action="/LogicAction" method ="post"> <h2>Enter text :</h2> <html:text property="text"/> <html:submit value="Submit"/> <html:cancel/> </html:form> </body> </html:html>

Developing the output.jsp page: Notice the property values

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <HTML> <HEAD> <TITLE>Here's Your Data...</TITLE>

</HEAD> <BODY> <H4>Here's Your Data...</H4> <h4>The text entered is: <bean:write name="LogicForm1" property="text"/></h4> <logic:present name="LogicForm1" property="text" > <h5>Using the tag &lt;logic:present &gt; </h5> Result: Successfully supported </logic:present>
<logic:notPresent name="LogicForm1" property="text1" > <h5>Using the tag&lt;logic:notPresent&gt;</h5> Result: Support for a Variable other than a String is not Present </logic:notPresent> </BODY> </HTML> Add the following line in the index.jsp to call the form. <li> <html:link page="/pages/InputLogic.jsp">Struts File Upload</html:link> <br> Example demonstrates how LogicAction Class works. </li> Building and Testing the Example To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the InputLogic.jsp page. Your browser displays the following page. Writing a text string to the InputLogic.jsp page lets you to see the working of the present Logic tag <logic:present > and the notPresent Logic tag <logic:notPresent >.

It displays the following out.jsp page

Developing Simple Struts Tiles Application Posted on: January 2, 2005 at 12:00 AM In this tutorial 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.

Developing Simple Struts Tiles Application

Introduction

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

What is Struts Tiles?


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

Steps To Create Tiles Application


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

1. 2. 3. 4.

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 file


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

<taglib> <taglib-uri>/tags/struts-tiles</taglib-uri> <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location> </taglib>

Create layout JSPs.

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

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

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 <tiles:insert attribute="header"/> inserts the header web page.

Develop the web pages using layouts


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

<p align="left"><font size="5">Welcome to the Title Tutorial</font></p> <p align="left"><font size="5">This is the content page</font></p>

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

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

<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"> 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 <tiles:put name="title" type="string" value="Welcome" /> is used. The following code is used to insert the actual pages in the template.: <tiles:put <tiles:put <tiles:put <tiles:put name="header" value="/tiles/top.jsp" /> name="menu" value="/tiles/left.jsp" /> name="body" value="/tiles/content.jsp" /> name="bottom" value="/tiles/bottom.jsp" />

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

Repackage, run and test application


Add the following code in the index.jsp to test the this tile example: <li> <html:link page="/tiles/example.jsp">Tiles Example</html:link> <br> Example of creating first tile application. </li> 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.

Struts File Upload Example Posted on: February 11, 2008 at 12:00 AM In this tutorial you will learn how to use Struts to write program to upload files.

Struts File Upload Example

In this tutorial you will learn how to use Struts to write program to upload files. The interface org.apache.struts.upload.FormFile is the heart of the struts file upload application. This interface represents a file that has been uploaded by a client. It is the only interface or class in upload package which is typically referenced directly by a Struts application. Creating Form Bean Our form bean class contains only one property theFile, which is of type org.apache.struts.upload.FormFile.

Here is the code of FormBean (StrutsUploadForm.java):


package roseindia.net;

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

/** * @author Deepak Kumar * @Web http://www.roseindia.net * @Email roseindia_net@yahoo.com */ /** * Form bean for Struts File Upload. * */ public class StrutsUploadForm extends ActionForm { private FormFile theFile; /** * @return Returns the theFile. */ public FormFile getTheFile() { return theFile; } /** * @param theFile The FormFile to set. */ public void setTheFile(FormFile theFile) { this.theFile = theFile; } }

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

package roseindia.net; import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.upload.FormFile; /** * @author Deepak Kumar * @Web http://www.roseindia.net * @Email roseindia_net@yahoo.com */ /** * Struts File Upload Action Form. * */ public class StrutsUploadAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ StrutsUploadForm myForm = (StrutsUploadForm)form; // Process the FormFile FormFile myFile = myForm.getTheFile(); String contentType = myFile.getContentType(); String fileName = myFile.getFileName(); int fileSize = myFile.getFileSize(); byte[] fileData = myFile.getFileData(); System.out.println("contentType: " + contentType); System.out.println("File Name: " + fileName); System.out.println("File Size: " + fileSize); return mapping.findForward("success"); } }

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

<form-bean name="FileUpload"

type="roseindia.net.StrutsUploadForm"/>

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

<action path="/FileUpload" type="roseindia.net.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/strutsbean" 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 are setting the encrypt property of the form to enctype="multipart/form-data". code for the success page (uploadsuccess.jsp) is:

<html> <head> <title>Success</title> </head>

<body> <p align="center"><font size="5" >File Successfully Received</font></p> </body> </html>

Add the following line in the index.jsp to call the form. <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 To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the FileUpload.jsp page. Your browser should display the file upload form:

Struts File Upload and Save

We are receiving lots of comments regarding "Struts file upload example". It does not contain any code illustrating how to save the file on the server . Now, the current example will provide you with the code to upload the file ,in the upload directory of server.
In this tutorial you will learn how to use Struts program to upload on the Server and display a link to the user to download the uploaded file . The interface org.apache.struts.upload.FormFile has a prime role in uploading a file in a Struts application. This interface represents a file that has been uploaded by a client. It is the only interface or class in Upload package which is referenced directly by a Struts application. Creating Form Bean

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

package roseindia.net;

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

/** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net */ /** * Form bean for Struts File Upload. * */ public class StrutsUploadAndSaveForm extends ActionForm { private FormFile theFile; /** * @return Returns the theFile. */ public FormFile getTheFile() { return theFile; } /** * @param theFile The FormFile to set. */ public void setTheFile(FormFile theFile) { this.theFile = theFile; } }

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

package roseindia.net; import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.upload.FormFile; import java.io.*; /** * @author Amit Gupta * @Web http://www.roseindia.net * @Email struts@roseindia.net */

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

// Process the FormFile FormFile myFile = myForm.getTheFile(); String contentType = myFile.getContentType();

//Get the file name String fileName = myFile.getFileName();

//int fileSize = myFile.getFileSize(); byte[] fileData = myFile.getFileData();

//Get the servers upload directory real path name String filePath = getServlet().getServletContext().getRealPath("/") +"upload"; /* Save file on the server */ if(!fileName.equals("")){ System.out.println("Server path:" +filePath); //Create file File fileToCreate = new File(filePath, fileName); //If file does not exists create file if(!fileToCreate.exists()){ FileOutputStream fileOutStream = new FileOutputStream(fileToCreate); fileOutStream.write(myFile.getFileData()); fileOutStream.flush(); fileOutStream.close(); } } //Set file name to the request object request.setAttribute("fileName",fileName);

return mapping.findForward("success"); } }
Defining form Bean in struts-config.xml file Add the following entry in the struts-config.xml file for defining the form bean:

<form-bean name="FileUploadAndSave" type="roseindia.net.StrutsUploadAndSaveForm"/>

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

<action path="/FileUploadAndSave" type="roseindia.net.StrutsUploadAndSaveAction" name="FileUploadAndSave" scope="request" validate="true" input="/pages/FileUploadAndSave.jsp"> <forward name="success" path="/pages/downloaduploadedfile.jsp"/> </action>

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

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <html:html locale="true"> <head> <title>Struts File Upload and Save Example</title> <html:base/> </head> <body bgcolor="white"> <html:form action="/FileUploadAndSave" method="post" enctype="multipart/form-data"> <table> <tr> <td align="center" colspan="2">

<font size="4">File Upload on Server</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>
code for the success page (downloaduploadedfile.jsp) is:

<html> <head> <title>Success</title> </head> <body>

<% String fileName=(String)request.getAttribute("fileName"); %> <p align="center"><font size="5" >File Successfully Received</font></p> <p align="center"><a href="upload/<%=fileName%>">Click here to download</a></p> </body> </html>
Add the following line in the index.jsp to call the form. <li> <html:link page="/pages/FileUploadAndSave.jsp">Struts File Upload</html:link> <br> Example shows you how to Upload File with Struts. </li> Building Example and Testing To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the Struts File Upload page. Your browser should display the file upload form:

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

Struts nested tag Example Posted on: February 27, 2008 at 12:00 AM

The tag library ?nested? is included in Struts 1.1. In this tutorial we are going to explain what are the features of nested tag library and how you can use it. We can manage nested beans easily with the help of struts nested tag library.

Struts nested tag Example

The tag library ?nested? is included in Struts 1.1. In this tutorial we are going to explain what are the features of nested tag library and how you can use it. We can manage nested beans easily with the help of struts nested tag library. Nested tags are used in the nested context. The Nested tags and its supporting classes extends the base struts tags and making them possible to relate to each other in the nested fashion. In case of Nested tags the original logic of the tags does not change and all the references to beans and bean properties is managed in the nested context. As far as bean is concerned, one is associated with another internally and access to all the beans are through the current one. The beans that refers to another is the parent and the second related to the first one is its child. Here both 'parent' and 'child' denotes a hierarchical structure of beans. For example, Take an object which represents a Author. Each author related to many book .If this case was translated to bean objects, the author object would have a reference to the book objects he wrote, and each bunch object would hold a reference to the chapters in the books. The author object is the parent to the books object, and the books object is a child of the author object. The books object is parent to its child chapters objects, and the child chapters objects children of the books object. The author is higher in the hierarchy than the books, and the chapters lower in the hierarchy to the books. Herbert Schildt Teach Yourself C++ Java: The Complete Reference, J2SE Struts: the complete reference O'Reilly .NET & XML ADO.NET in a Nutshell ADO: ActiveX Data Objects Create a new struts 1.1 project to to understand nested tags. Object Class Books Create a class Books with properties id and name in the package roseindia.web.common. Add a getter and setter method for each property. Also add a constructor that initialize the properties. Books.java

package roseindia.web.common; public class Books { private int id; private String name; //constructors public Books(){} public Books(int id, String name){ this.id = id; this.name = name;

} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Object Class Authors Create a second java class Authors in the same package roseindia.web.common. Add two properties, id of type int and name of type String and one property books of type Collection, which holds a list of books. Add a getter and setter method for each property. Also add a constructor that initialize the properties. Authors.java

package roseindia.web.common; import java.util.*; public class Authors { private int id; private String name; //books collection private Collection books; //constructors public Authors() {} public Authors(int id, String name, Collection books){ this.id = id; this.name = name; this.books = books; } public Collection getBooks() { return books; } public void setBooks(Collection books) { this.books = books; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name;

} }
Action form class AuthorsBooksForm Create a java class AuthorsBooksForm in the package roseindia.web.struts.form, which extends the class ActionForm of struts. Add a property authors of type Authors . Add a getter and setter method for the property authors . Implement the reset() method of the ActionForm class. AuthorsBooksForm.java

package roseindia.web.struts.form; import java.util.*; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import roseindia.web.common.Authors; import roseindia.web.common.Books; public class AuthorsBooksForm extends ActionForm { Authors authors; public void setAuthors(Authors authors) { this.authors = authors; } public Authors getAuthors() { return authors; } public void reset(ActionMapping mapping,HttpServletRequest request) { //initial a dummy collection of books Collection books = new ArrayList(); books.add(new Books(1, "Teach Yourself C++")); books.add(new Books(2, "Java: The Complete Reference, J2SE")); books.add(new Books(3, "Struts: The Complete Reference")); //initial a dummy authors authors = new Authors(1, "Herbert Schildt", books); } }
Action class AuthorsBooksAction Create a java class AuthorsBooksAction in the package roseindia.web.struts.action, which extends the class Action of struts. Return the forward example. AuthorsBooksAction.java

package roseindia.web.struts.action; import roseindia.web.struts.form.AuthorsBooksForm;

import import import import import import import

javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; java.util.*; org.apache.struts.action.Action; org.apache.struts.action.ActionForm; org.apache.struts.action.ActionForward; org.apache.struts.action.ActionMapping;

public class AuthorsBooksAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { AuthorsBooksForm booksForm = (AuthorsBooksForm) form; return mapping.findForward("books"); } }
The JSP file Create a new JSP file authorsbooks.jsp. Add the reference to the tag library nested at the top of the file. authorsbooks.jsp

<%@ <%@ <%@ <%@ <%@

page language="java"%> taglib uri="/tags/struts-bean" prefix="bean" %> taglib uri="/tags/struts-html" prefix="html" %> taglib uri="/tags/struts-logic" prefix="logic" %> taglib uri="/tags/struts-nested" prefix="nested"%> <head>

<html> <title>Struts nested tag Example</title> </head> <body> <h1>Struts nested tag Example</h1> <b>Author and his books:</b> <html:form action="/example" method="post"> <nested:nest property="authors"> <b><nested:write property="name"/> </b> <nested:iterate property="books">

<ul><li><nested:write property="name"/></li></ul> </nested:iterate> </nested:nest>


</html:form> </body> </html>

Configure the struts-config.xml Open the struts-config.xml and add the form bean and action mapping. struts-config.xml

<form-beans> <form-bean name="AuthorsBooksForm" type="roseindia.web.struts.form.AuthorsBooksForm" /> </form-beans> <action-mappings> <action path="/example" type="roseindia.web.struts.action.AuthorsBooksAction" input="/pages/user/authorsbooks.jsp" name="AuthorsBooksForm" scope="request" validate="false"> <forward name="example" path="/pages/user/authorsbooks.jsp" /> </action> </action-mappings>
Output: To view the output run the authorsbooks.jsp from the browser.

Building and Testing Struts Hibernate Plugin Application Posted on: January 21, 2008 at 12:00 AM In this section we will build and test our Struts Hibernate Integration application.

Building and Testing Struts Hibernate Plugin Application

In this section we will build and test our Struts Hibernate Integration application. Compiling and packaging application Since we are using ant build tool, so the compiling and packaging will done by ant tool. To compile and create war file for deployment, open console and go to "C:\Struts-Hibernate-Integration\code\WEB-INF\src" directory. Then just type ant, ant will create strutshibernate.war in the "C:\Struts-Hibernate-Integration\dist" directory. Deploying and testing application Copy strutshibernate.war to the webapps directory of tomcat and start tomcat server. Now open the browser and type http://localhost:8080/strutshibernate/ in the browser. You browser should look like:

Now click on "Click here to test Search Tutorials" link.

Enter some search term say "java" and click on search button. You browser should display the search result as shown below.

Congratulations now you have successfully integrated your struts application with hibernate using Hibernate Struts Plugin. You can download the code of this application from here.

Developing Struts Hibernate Plugin Posted on: January 19, 2008 at 12:00 AM In this section we will develop java code for Struts Hibernate Plugin.

Developing Struts Hibernate Plugin

In this section we will develop java code for Struts Hibernate Plugin. Our Hibernate Plugin will create Hibernate Session factory and cache it in the servlet context. This strategy enhances the performance of the application. Source Code Of Hibernate Struts Plugin:

package roseindia.net.plugin;

import java.net.URL; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; import org.hibernate.HibernateException;

public class HibernatePlugIn implements PlugIn { private String _configFilePath = "/hibernate.cfg.xml"; /** * the key under which the <code>SessionFactory </code> instance is stored * in the <code>ServletContext</code>. */ public static final String SESSION_FACTORY_KEY = SessionFactory.class.getName(); private SessionFactory _factory = null; public void destroy() { try{ _factory.close(); }catch(HibernateException e){ System.out.println("Unable to close Hibernate Session Factory: " + e.getMessage()); } } public void init(ActionServlet servlet, ModuleConfig config) throws ServletException { System.out.println("*************************************"); System.out.println("**** Initilizing HibernatePlugIn **********"); Configuration configuration = null; URL configFileURL = null; ServletContext context = null;

try{ configFileURL = HibernatePlugIn.class.getResource(_configFilePath); context = servlet.getServletContext(); configuration = (new Configuration()).configure(configFileURL); _factory = configuration.buildSessionFactory(); //Set the factory into session context.setAttribute(SESSION_FACTORY_KEY, _factory); }catch(HibernateException e){ System.out.println("Error while initializing hibernate: " + e.getMessage()); } System.out.println("**************** *********************"); } /** * Setter for property configFilePath. * @param configFilePath New value of property configFilePath. */ public void setConfigFilePath(String configFilePath) { if ((configFilePath == null) || (configFilePath.trim().length() == 0)) { throw new IllegalArgumentException("configFilePath cannot be blank or null."); } System.out.println("Setting ' configFilePath' to '" + configFilePath + "'..."); _configFilePath = configFilePath; }

/*(SessionFactory) servletContext.getAttribute (HibernatePlugIn.SESSION_FACTORY_KEY); */ }

In our plugin class we have define a variable _configFilePath to hold the name of Hibernate Configuration file. private String _configFilePath = "/hibernate.cfg.xml"; Following code define the key to store the session factory instance in the Servlet context.

public static final String SESSION_FACTORY_KEY = SessionFactory.class.getName(); The init() is called on the startup of the Struts Application. On startup the session factory is initialized and cached in the Servlet context. configFileURL = HibernatePlugIn.class.getResource(_configFilePath); context = servlet.getServletContext(); configuration = (new Configuration()).configure(configFileURL); _factory = configuration.buildSessionFactory(); //Set the factory into session context.setAttribute(SESSION_FACTORY_KEY, _factory); Changes to be done in struts-config.xml file Configuring Hibernate with Struts is very simple work it requires you to have hibernate.cfg.xml in your WEB-INF/classes directory, and to add the following line to the struts-config.xml file. <plug-in className="roseindia.net.plugin.HibernatePlugIn"></plug-in> Testing the Plugin Build your application and deploy on the tomcat server. Start tomcat server and observe the console output. It should display the following line:

log4j:WARN Please initialize the log4j system properly. ************************************* **** Initilizing HibernatePlugIn ********** ************************************* Aug 7, 2006 10:09:53 AM org.apache.struts.tiles.TilesPlugin initD

This means you have successfully configured your Struts Hibernate Plugin with struts application.

You might also like