Sei sulla pagina 1di 35

1

Index

No 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

Subject
Struts MVC Architecture Hello World Example in Eclipse Hello World Application Login Application Using Action Form DispatchAction Class LookupDispatchAction Class Struts Select HTML Tag Struts HTML Tag Struts Logic Tag

Page No 2 3 10 15 20 23 27 30 33

Created by : Jignesh S. Prajapati

1. Struts MVC Architecture


The model contains the business logic and interact with the persistance storage to store, retrive and manipulate data. The view is responsible for dispalying the results back to the user. In Struts the view layer is implemented using JSP. The controller handles all the request from the user and selects the appropriate view to return. In Sruts the controller's job is done by the ActionServlet.

The following events happen when the Client browser issues an HTTP request. The ActionServlet receives the request. The struts-config.xml file contains the details regarding the Actions, ActionForms,ActionMappings and ActionForwards. During the startup the ActionServelet reads the struts-config.xml file and creates a database of configuration objects. Later while processing the request the ActionServletmakes decision by refering to this object. When the ActionServlet receives the request it does the following tasks. Bundles all the request values into a JavaBean class which extends Struts ActionForm class. Decides which action class to invoke to process the request. Validate the data entered by the user. The action class process the request with the help of the model component. The model interacts with the database and process the request. After completing the request processing the Action class returns an ActionForward to the controller. Based on the ActionForward the controller will invoke the appropriate view. The HTTP response is rendered back to the user by the view component.

Created by : Jignesh S. Prajapati

2. Hello World Example in Eclipse


you will learn how to create a Struts hello world application in eclipse. First create a new project, go to File->New and select DynamicWebProject.

Enter the project name and click the Finish button.

Created by : Jignesh S. Prajapati

Add the following jar files to the WEB-INF\lib directory.

Right click the src folder and select New->Package.

Enter the package name as com.vaannila.form and click Finish.

Created by : Jignesh S. Prajapati

Now right click the newly created package and select New->Class.

Created by : Jignesh S. Prajapati

Enter the class name as HelloWorldForm and asorg.apache.struts.action.ActionForm and click Finish.

the

superclass

name

In the HelloWorldForm class add the following code. 01.package com.vaannila.form; 02. 03.import org.apache.struts.action.ActionForm; 04. 05.public class HelloWorldForm extends ActionForm { 06. 07.private static final long serialVersionUID = -473562596852452021L; 08. 09.private String message; 10. 11.public String getMessage() { 12.return message;

Created by : Jignesh S. Prajapati

7
13.} 14. 15.public void setMessage(String message) { 16.this.message = message; 17.} 18.} In the same way create a new package com.vaannila.action and create a HelloWorldAction class extending org.apache.struts.action.Action. Add the following code to the action class and save it. 01.package com.vaannila.action; 02. 03.import javax.servlet.http.HttpServletRequest; 04.import javax.servlet.http.HttpServletResponse; 05. 06.import org.apache.struts.action.Action; 07.import org.apache.struts.action.ActionForm; 08.import org.apache.struts.action.ActionForward; 09.import org.apache.struts.action.ActionMapping; 10. 11.import com.vaannila.form.HelloWorldForm; 12. 13.public class HelloWorldAction extends Action { 14. 15.@Override 16.public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { 17.HelloWorldForm hwForm = (HelloWorldForm) form; 18.hwForm.setMessage("Hello World"); 19.return mapping.findForward("success"); 20.} 21.} Here we typecast the ActionForm to HelloWorldForm and set the message value. Add the following entries in the struts-config.xml file. 01.<?xml version="1.0" encoding="ISO-8859-1" ?> 02. 03.<!DOCTYPE struts-config PUBLIC 04."-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 05."http://struts.apache.org/dtds/struts-config_1_3.dtd"> 06. 07.<struts-config> 08. 09.<form-beans> 10.<formbean name="helloWorldForm"type="com.vaannila.form.HelloWorldForm"/> 11.</form-beans> 12. 13.<global-forwards> 14.<forward name="helloWorld" path="/helloWorld.do"/> 15.</global-forwards> 16. 17.<action-mappings>

Created by : Jignesh S. Prajapati

8
18.<action path="/helloWorld" type="com.vaannila.action.HelloWorldAction"nam e="helloWorldForm"> 19.<forward name="success" path="/helloWorld.jsp" /> 20.</action> 21.</action-mappings> 22. 23.</struts-config> Now configure the deployment descriptor. Add the following configuration information in the web.xmlfile. 01.<?xml version="1.0" encoding="UTF-8"?> 02.<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:web="http://java.su n.com/xml/ns/javaee/webapp_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" id="WebApp_ID"version="2.5"> 03.<display-name>StrutsExample1</display-name> 04. 05.<servlet> 06.<servlet-name>action</servlet-name> 07.<servlet-class>org.apache.struts.action.ActionServlet</servlet-class> 08.<init-param> 09.<param-name>config</param-name> 10.<param-value>/WEB-INF/struts-config.xml</param-value> 11.</init-param> 12.<load-on-startup>2</load-on-startup> 13.</servlet> 14. 15.<servlet-mapping> 16.<servlet-name>action</servlet-name> 17.<url-pattern>*.do</url-pattern> 18.</servlet-mapping> 19. 20.<welcome-file-list> 21.<welcome-file>index.jsp</welcome-file> 22.</welcome-file-list> 23.</web-app> When we run the application the index.jsp page will be executed first. In the index.jsp page we redirect the request to the helloWorld.do URI, which inturn invokes the HelloWorldAction. 1.<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %> 2.<logic:redirect forward="helloWorld"/> In the action class we return the ActionForward "success" which is mapped to the helloWorld.jsppage. In the helloWorld.jsp page we display the "Hello World" message. 01.<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> 02.<html> 03.<head> 04.<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 05.<title>Hello World</title> 06.</head> 07.<body> 08.<bean:write name="helloWorldForm" property="message"/> 09.</body> 10.</html>

Created by : Jignesh S. Prajapati

After creating all the files the directory structure of the application looks like this.

On executing the application the "Hello World" message gets displayed to the user.

You can download the source code of this example by clicking on the Download link below.
Source :Download War :Download

Created by : Jignesh S. Prajapati

10

3. Hello World Application


Lets say a quick hello to struts. Struts follows MVC 2 pattern. The following files are needed to create a hello world application. index.jsp helloWorld.jsp web.xml struts-config.xml HelloWorldAction.java HelloWorldActionForm.java

Created by : Jignesh S. Prajapati

11
web.xml

web.xml is used to configure the servlet container properties of the hello world appliation. 1.<welcome-file-list> 2.<welcome-file>index.jsp</welcome-file> 3.</welcome-file-list> The gateway for our hello world application is index.jsp file. The index.jsp file should be mentioned in web.xml as shown above.
index.jsp

In the hello world example the index.jsp page simply forwards the request to the hello world action. 1.<jsp:forward page="HelloWorld.do"/>
struts-config.xml

struts-config.xml file is used to configure the struts framework for the hello world application. This file contains the details regarding the form bean and the action mapping. 01.<struts-config> 02. 03.<form-beans> 04.<form-bean name="HelloWorldActionForm" 05.type="com.vaannila.HelloWorldActionForm"/> 06.</form-beans> 07. 08.<action-mappings> 09.<action input="/index.jsp" name="HelloWorldActionForm"path="/HelloWorld" scope="session"type="com.vaannila.HelloWorldAction"> 10.<forward name="success" path="/helloWorld.jsp" /> 11.</action> 12.</action-mappings> 13. 14.</struts-config>

Created by : Jignesh S. Prajapati

12

HelloWorldActionForm.java

HelloWorldActionForm extends org.apache.struts.action.ActionForm. HelloWorldActionForm class has one String variable message and the corresponding getter and setter methods. 01.public class HelloWorldActionForm extends 02.org.apache.struts.action.ActionForm { 03. 04.private String message; 05. 06.public HelloWorldActionForm() { 07.super(); 08.} 09. 10.public String getMessage() { 11.return message; 12.} 13. 14.public void setMessage(String message) { 15.this.message = message; 16.} 17. 18.}

Created by : Jignesh S. Prajapati

13

HelloWorldAction.java

HelloWorldAction class extends org.apache.struts.action.Action. The action class contains an execute method which contains the business logic of the application. To access the HelloWorldActionForm variables in the Action we need to type caste the form object to HelloWorldActionForm. Then we can access the variables using the getter and setter methods. The execute method returns a value of type ActionForward, based on its value the corresponding view will be called. This configuration is done in struts-config.xml file. 01.public class HelloWorldAction extends org.apache.struts.action.Action { 02. 03.private final static String SUCCESS = "success"; 04. 05.public ActionForward execute(ActionMapping mapping,ActionForm form, 06.HttpServletRequest request,HttpServletResponse response) throwsException { 07. 08.HelloWorldActionForm helloWorldForm = (HelloWorldActionForm) form; 09.helloWorldForm.setMessage("Hello World!"); 10.return mapping.findForward(SUCCESS); 11. 12.} 13.} 1.<action-mappings> 2.<action input="/index.jsp" name="HelloWorldActionForm" path="/HelloWorld" 3.scope="session" type="com.vaannila.HelloWorldAction"> 4.<forward name="success" path="/helloWorld.jsp" /> 5.</action> 6.</action-mappings> The name "success" is mapped to the view helloWorld.jsp. So when the execute method in the action returns "success" the request will be forwarded to the helloWold.jsp page.

Created by : Jignesh S. Prajapati

14

helloWorld.jsp

In helloWorld.jsp we get the value of the form variable message and display it. We use struts bean tag to do this. The name attribute of the bean tag hold the value of the action form and the property attribute holds the value of the variable to be displayed. 01.<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> 02.<html> 03.<head> 04.<title>Hello World</title> 05.</head> 06.<body> 07.<h1> 08.<bean:write name="HelloWorldActionForm" property="message" /> 09.</h1> 10.</body> 11.</html> Extract the downloaded files into the webapps folder of the Tomcat server. Start the Tomcat server. Type the following url in the browser "http://localhost:8080/Example1/index.jsp". There you go, you have your first struts program up and running.

You can download the source code of the Hello World example by clicking on the Download link below.
Source :Download Source + Lib :Download

Created by : Jignesh S. Prajapati

15

4. Login Application Using Action Form


In this example we will see how to create a login application using ActionForm. The following files are required for the login application. login.jsp success.jsp failure.jsp web.xml struts-config.xml LoginAction.java LoginForm.java ApplicationResource.properties
web.xml

The first page that will be called in the login application is the login.jsp page. This configuration should be done in web.xml as shown below. 1.<welcome-file-list> 2.<welcome-file>login.jsp</welcome-file> 3.</welcome-file-list>

login.jsp

We use Struts HTML Tags to create login page. The form has one text field to get the user name and one password field to get the password. The form also has one submit button, which when clicked calls the login action. <html:errors /> tag is used to display the error messages to the user. 01.<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> 02.<html> 03.<head> 04.<title>Login Page</title> 05.</head> 06.<body> 07.<div style="color:red"> 08.<html:errors /> 09.</div> 10.<html:form action="/Login" > 11.User Name :<html:text name="LoginForm" property="userName" /> 12.Password :<html:password name="LoginForm" property="password" /> 13.<html:submit value="Login" /> 14.</html:form> 15.</body> 16.</html> The user enters the user name and password and clicks the login button. The login action is invoked.

Created by : Jignesh S. Prajapati

16

struts-config.xml

The validate method in the LoginForm class is called when the Form is submitted. If any errors are found then the control is returned back to the input page where the errors are displayed to the user. The input page is configured in the action tag of strut-config file. <html:errors /> tag is used to display the errors in the jsp page. 01.<struts-config> 02.<form-beans> 03.<form-bean name="LoginForm" type="com.vaannila.LoginForm"/> 04.</form-beans> 05. 06.<action-mappings> 07.<action input="/login.jsp" name="LoginForm" path="/Login"scope="session" t ype="com.vaannila.LoginAction"> 08.<forward name="success" path="/success.jsp" /> 09.<forward name="failure" path="/failure.jsp" /> 10.</action> 11.</action-mappings> 12.</struts-config> Here the action is "/Login" , the input page is "login.jsp" and the corresponding action class is LoginAction.java. Now the validate method in the LoginForm class will be invoked.
LoginForm.java

Inside the validate method, we check whether the user name and password is entered. If not the corresponding error message is displayed to the user. The error messages are configured in the ApplicationResource.properties file. 01.public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { 02.ActionErrors errors = new ActionErrors(); 03.if (userName == null || userName.length() < 1) { 04.errors.add("userName", new ActionMessage("error.userName.required")); 05.} 06.if (password == null || password.length() < 1) { 07.errors.add("password", new ActionMessage("error.password.required")); 08.} 09.return errors; 10.}

Created by : Jignesh S. Prajapati

17

ApplicationResource.properties

The ApplicationResource.properties file contains the error messages. The key "error.userName.required" is used in the validate function to add a new error. Since the error messages are configured in a seperate properties file they can be changed anytime without making any changes to the java files or the jsp pages. 1.error.userName.required = User Name is required. 2.error.password.required = Password is required. If either user name or password is not entered then the corresponding error message will be added to the ActionErrors. If any errors are found then the control is returned back to the input jsp page, where the error messages are displayed using the <html:errors /> tag. The validate method is used to perform the client-side validations. Once when the input data is valid the execute method in the LoginAction class is called.
LoginAction.java

The execute method contains the business logic of the application. Here first we typecast the ActionForm object to LoginForm, so that we can access the form variables using the getter and setter methods. If the user name and password is same then we forward the user to the success page else we forward to the failure page. 01.public class LoginAction extends org.apache.struts.action.Action { 02. 03.private final static String SUCCESS = "success"; 04.private final static String FAILURE = "failure"; 05. 06.public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throwsException { 07.LoginForm loginForm = (LoginForm) form; 08.if (loginForm.getUserName().equals(loginForm.getPassword())) { 09.return mapping.findForward(SUCCESS); 10.} else { 11.return mapping.findForward(FAILURE); 12.} 13.} 14.} Lets enter the user names and password as "Eswar". Since the user name and password is same the execute method will return an ActionForward "success". The corresponding result associated with the name "success" will be shown to the user. This configuration is done in struts-config.xml file.

Created by : Jignesh S. Prajapati

18
1.<action-mappings> 2.<action input="/login.jsp" name="LoginForm" path="/Login" scope="session"ty pe="com.vaannila.LoginAction"> 3.<forward name="success" path="/success.jsp" /> 4.<forward name="failure" path="/failure.jsp" /> 5.</action> 6.</action-mappings> So according to the configuration in struts-config.xml the user will be forwarded to success.jsp page.

Created by : Jignesh S. Prajapati

19

If the user name and password did not match the user will be forwarded to the failure page. Lets try entering "Joe" as the user name and "Eswar" as the password, the following page will be displayed to the user.

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

Source :Download Source + Lib :Download

Created by : Jignesh S. Prajapati

20

5. DispatchAction Class
DispatchAction provides a mechanism for grouping a set of related functions into a single action, thus eliminating the need to create seperate actions for each functions. In this example we will see how to group a set of user related actions like add user, update user and delete user into a single action called UserAction. The class UserAction extends org.apache.struts.actions.DispatchAction. This class does not provide an implementation of the execute() method as the normal Action class does. The DispatchAction uses the execute method to manage delegating the request to the individual methods based on the incoming request parameter. For example if the incoming parameter is "method=add", then the add method will be invoked. These methods should have similar signature as the execute method. 01.public class UserAction extends DispatchAction { 02. 03.private final static String SUCCESS = "success"; 04. 05.public ActionForward add(ActionMapping mapping, ActionForm form, 06.HttpServletRequest request, HttpServletResponse response) 07.throws Exception { 08.UserForm userForm = (UserForm) form; 09.userForm.setMessage("Inside add user method."); 10.return mapping.findForward(SUCCESS); 11.} 12. 13.public ActionForward update(ActionMapping mapping, ActionForm form, 14.HttpServletRequest request, HttpServletResponse response) 15.throws Exception { 16.UserForm userForm = (UserForm) form; 17.userForm.setMessage("Inside update user method."); 18.return mapping.findForward(SUCCESS); 19.} 20. 21.public ActionForward delete(ActionMapping mapping, ActionForm form, 22.HttpServletRequest request, HttpServletResponse response) 23.throws Exception { 24.UserForm userForm = (UserForm) form; 25.userForm.setMessage("Inside delete user method."); 26.return mapping.findForward(SUCCESS); 27.} 28.} If you notice the signature of the add, update and delete methods are similar to the execute method except the name. The next step is to create an action mapping for this action handler. The request parameter name is specified using the parameter attribute. Here the request parameter name is method. 1.<action-mappings> 2.<action input="/index.jsp" parameter="method" name="UserForm"path="/UserAc tion" scope="session" type="com.vaannila.UserAction"> 3.<forward name="success" path="/index.jsp" /> 4.</action> 5.</action-mappings> Now lets see how to invoke a DispatchAction from jsp. We have a simple form with three buttons to add, update and delete a user. When each button is clicked a different

Created by : Jignesh S. Prajapati

21
method in UserAction class is invoked. 01.<html> 02.<head> 03.<script type="text/javascript"> 04.function submitForm() 05.{ 06.document.forms[0].action = "UserAction.do?method=add" 07.document.forms[0].submit(); 08.} 09.</script> 10.</head> 11.<body> 12.<html:form action="UserAction" > 13.<table> 14.<tr> 15.<td> 16.<bean:write name="UserForm" property="message" /> 17.</td> 18.</tr> 19.<tr> 20.<td> 21.<html:submit value="Add" onclick="submitForm()" /> 22.</td> 23.</tr> 24.<tr> 25.<td> 26.<html:submit property="method" value="update" /> 27.</td> 28.</tr> 29.<tr> 30.<td> 31.<html:submit property="method" >delete</html:submit> 32.</td> 33.</tr> 34.</table> 35.</html:form> 36.</body> 37.</html> Now consider the update and the delete button. The request parameter name specified in the action handler is "method". So this should be specified as the property name for the submit button. The name of the method to be invoked and the value of the button should be the same. So when the button is clicked the corresponding method in the UserAction will be called. The delete button shows an alternate way to specify the value of the button. Here the main constraint is the method name and the button name should be same. So we can't have an update button like this "Update". Inorder to avoid this you can call a javascript function on click of the button. Specify the action and submit the form from javascript. In this way we can have a different button name and method name. On click of the Add button the action value is set to "UserAction.do?method=add" and the form is submitted from javascript.

Created by : Jignesh S. Prajapati

22

On executing the sample example the following page is displayed to the user.

After clicking the add button the following page is displayed.

You can download the source code of the DispatchAction example by clicking on the Download link below.
Source :Download Source + Lib :Download

Created by : Jignesh S. Prajapati

23

6. LookupDispatchAction Class
LookupDispatchAction provides a mechanism for grouping a set of related functions into a single action, thus eliminating the need to create seperate actions for each functions. In this example we will see how to group a set of user related actions like add user, update user and delete user into a single action called UserAction. The LookupDispatchAction class extends org.apache.struts.actions.DispatchAction. Our class UserAction class extends LookupDispacthAction. This class does not provide an implementation of the execute() method as the normal Action class does. The LookupDispatchAction uses the execute method to manage delegating the request to the individual methods based on the incoming request parameter. 01.public class UserAction extends LookupDispatchAction { 02. 03.private final static String SUCCESS = "success"; 04. 05.protected Map getKeyMethodMap() { 06.Map map = new HashMap(); 07.map.put("UserForm.add", "add"); 08.map.put("UserForm.update", "update"); 09.map.put("UserForm.delete", "delete"); 10.return map; 11.} 12. 13.public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throwsException { 14.UserForm userForm = (UserForm) form; 15.userForm.setMessage("Inside add user method."); 16.return mapping.findForward(SUCCESS); 17.} 18. 19.public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throwsException { 20.UserForm userForm = (UserForm) form;

Created by : Jignesh S. Prajapati

24
21.userForm.setMessage("Inside update user method."); 22.return mapping.findForward(SUCCESS); 23.} 24. 25.public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throwsException { 26.UserForm userForm = (UserForm) form; 27.userForm.setMessage("Inside delete user method."); 28.return mapping.findForward(SUCCESS); 29.} 30. 31.} If you notice the signature of the add, update and delete methods are similar to the execute method except the name. The UserAction class must provide an implementation of getKeyMethodMap()method. This method maps the methods in the action class to keys in the Struts resource bundle file. The next step is to create an action mapping for this action handler. The request parameter name is specified using the parameter attribute. Here the request parameter name is method. 1.<action-mappings> 2.<action input="/index.jsp" parameter="method" name="UserForm"path="/UserAc tion" scope="session" type="com.vaannila.UserAction"> 3.<forward name="success" path="/index.jsp" /> 4.</action> 5.</action-mappings>
getKeyMethodMap()

The getKeyMethodMap() method contains a HashMap. The names in the resource bundle file are the keys for this map and the corresponding values are the method names in the action class. For example the key value in the ApplicationResource.properties file is "UserForm.add" and the corresponding method name is "add" in the UserAction class. The main constraint in the DispatchAction is the method name in the action class and the button name in the jsp page should be the same. But here in LookupDispatchAction, we can have different names for the buttons and the methods. In ApplicationResource.properties file each key is mapped to a value, that value represents the button name in the jsp page. In the getKeyMethodMap() method the same key is mapped to a different value, this value corresponds to the method name to be invoked in the action class. 1.ApplicationResource.properties

Created by : Jignesh S. Prajapati

25
2.-----------------------------3.UserForm.add = Add 4.UserForm.update = Update 5.UserForm.delete = Delete 01.UserAction.java 02.--------------03.protected Map getKeyMethodMap() { 04.Map map = new HashMap(); 05.map.put("UserForm.add", "add"); 06.map.put("UserForm.update", "update"); 07.map.put("UserForm.delete", "delete"); 08.return map; 09.} Here "Add", "Update" and "Delete" are the button names and "add", "update" and "delete" are the corresponding method names. If you want to change the name of the button at the later stage, you can easily do so by just changing the value in the ApplicationResource.properties file without making any changes to the jsp page. The struts-config.xml file contains the following action mapping. 1.<action-mappings> 2.<action input="/index.jsp" name="UserForm" parameter="method"path="/UserAc tion" scope="session" type="com.vaannila.UserAction"> 3.<forward name="success" path="/index.jsp" /> 4.</action> 5.</action-mappings> The value of the parameter attribute of the action tag will be used as the request parameter and it's value will determine which method in the action class will be invoked. For example when the "Add"button is clicked the request parameter value will be "method=UserForm.add" and it will invoke the corresponding "add" method in the UserAction.

Created by : Jignesh S. Prajapati

26

On clicking the add button the following page is displayed.

You can download the source code of the Struts LookupDispatchAction example by clicking on the Download link below.
Source :Download Source + Lib :Download

Created by : Jignesh S. Prajapati

27

7. Struts Select HTML Tag


In this example we will see two different methods to populate a dropdown box in the jsp page. We use HTML select tag to do this. The dropdown values are stored in two ArrayList namely countryList and stateList. We use HTML optionsCollection tag to display the values present in the ArrayList. In order to use the Struts HTML Tags you need to include the following taglib directive in the jsp page. 1.<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> To use the Struts HTML Tag Library you need to add the following <taglib> subelement to the web.xml file. 1.<taglib> 2.<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri> 3.<taglib-location>/WEB-INF/struts-html.tld</taglib-location> 4.</taglib> The jsp page contains two dropdowns one for displaying the country and the other for displaying the state. The jsp page contains the following code. 01.<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> 02.<html> 03.<head> 04.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 05.<title>JSP Page</title> 06.</head> 07.<body> 08.<html:form action="/inputAction" > 09.<table> 10.<tr> 11.<td> 12.Select Country : 13.</td> 14.<td> 15.<html:select property="country" > 16.<html:option value="0">Select Country</html:option> 17.<html:optionsCollection name="InputForm"property="countryList" label="cou ntryName" value="countryId"/> 18.</html:select> 19.</td> 20.</tr> 21.<tr> 22.<td> 23.Select State : 24.</td> 25.<td> 26.<html:select property="state" > 27.<html:option value="0">Select State</html:option> 28.<html:optionsCollection name="InputForm" property="stateList"label="label " value="value" /> 29.</html:select> 30.</td> 31.</tr> 32.<tr> 33.<td colspan="2" align="center"> 34.<html:submit property="method" value="save" /> 35.</td>

Created by : Jignesh S. Prajapati

28
36.</tr> 37.</table> 38.</html:form> 39.</body> 40.</html> The CountryData class is used to hold the details regarding the country. The CountryData class has countryId and countryName as attributes and the corresponding getter and setter methods. In the jsp page we use the following code to display the country list. 1.<html:select property="country" > 2.<html:option value="0">Select Country</html:option> 3.<html:optionsCollection name="InputForm" property="countryList" 4.label="countryName" value="countryId" /> 5.</html:select> Here we need to display the countryName as the label and the countryId as the corresponding value. We do this using the label and the value attribute of the HTML optionsCollection tag. The property attribute of the HTML optionsCollection tag holds the ArrayList. The property attribute of the HTML select tag hold the country value selected by the user. The input form contains the following attributes. 1.// holds the country selected by the user 2.private String country; 3.// holds the state selected by the user. 4.private String state; 5.// holds the list of countries to be displayed. 6.private ArrayList countryList; 7.// holds the list of state to be displayed. 8.private ArrayList stateList; Here we use DispatchAction. One method is used to populate the values and the other method is used to save the selected values. Inside the populate method we populate the values for countryList and the stateList. The following code is used to add a list of countries to the countryList. 1.ArrayList countryList = new ArrayList(); 2.countryList.add(new CountryData("1", "USA")); 3.countryList.add(new CountryData("2", "Canada")); 4.countryList.add(new CountryData("3", "Mexico")); We add CountryData object inside the countryList. Creating a seperate class like this and adding it to ArrayList will be helpful if we have a few more attributes and methods corresponding to it other than the label and value. If we have only label and value then we can use the LabelValueBean class to add the label and value to the ArrayList. We populate the stateList using the LabelValueBean class. The following code is used to populate the stateList in the action class. 1.ArrayList stateList = new ArrayList(); 2.stateList.add(new LabelValueBean("New York", "1")); 3.stateList.add(new LabelValueBean("California", "2")); 4.stateList.add(new LabelValueBean("Los Angeles", "3"));

Created by : Jignesh S. Prajapati

29
The following code is used to dispaly the state list in the jsp page. 1.<html:select property="state" > 2.<html:option value="0">Select State</html:option> 3.<html:optionsCollection name="InputForm" property="stateList" 4.label="label" value="value" /> 5.</html:select> On executing the example the following page will be dispalyed to the user.

The country and the state dropdowns are populate with the values present in the array list.

You can download the source code of the HTML Select Tag example by clicking on the Download link below.
Source :Download Source + Lib :Download

Created by : Jignesh S. Prajapati

30

8. Struts HTML Tag


In this example you will learn how to use Struts HTML Tags. In order to use the Struts HTML Tags you need to include the following taglib directive in the jsp page. 1.<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> All the Struts HTML tags should be nested within the body of the <html:form /> tag. We will create a simple feedback form to see how the different Struts HTML Tags can be used. The feedback.jsp contains the following code. 01.<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> 02.<html> 03.<head> 04.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 05.<title>Feedback Form</title> 06.</head> 07.<body> 08.<b>Feedback Form</b> 09.<hr> 10.<html:form action="/feedbackAction"> 11.<table> 12.<tr> 13.<td> 14.Name : 15.</td> 16.<td> 17.<html:text name="feedbackForm" property="name" /> 18.</td> 19.</tr> 20.<tr> 21.<td> 22.Sex : 23.</td> 24.<td> 25.<html:radio name="feedbackForm" property="sex" value="M" > 26.M </html:radio> 27.<html:radio name="feedbackForm" property="sex" value="F" > 28.F </html:radio> 29.</td> 30.</tr> 31.<tr> 32.<td> 33.Comments : 34.</td> 35.<td> 36.<html:textarea cols="20" rows="5" name="feedbackForm" 37.property="comments" /> 38.</td> 39.</tr> 40.<tr> 41.<td> 42.<html:submit /> 43.</td> 44.<td> 45.<html:reset /> 46.</td> 47.</tr> 48.</table>

Created by : Jignesh S. Prajapati

31
49.</html:form> 50.</body> 51.</html> The name attribute of the HTML tag contains the Form Bean name. The property attribute of the HTML Tag contains the corresponding Form property. Once the feedback is submitted by the user, the user will be forwarded to the success page. Here the feedback submitted by the user will be displayed. We use Struts Bean Tag do to this. We use Struts Logic Equal Tag to display Male if the user has selected M for sex and Female if the user has selected F for sex. In order to use the Struts Bean and Logic Tag you need to include the following taglib directives in the jsp page. 1.<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> 2.<%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> The success.jsp page contains the following code. 01.<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> 02.<%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> 03.<html> 04.<head> 05.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 06.<title>Feedback Form</title> 07.</head> 08.<body> 09.<b>Feedback Successfully Submitted.</b><br> 10.You have submitted the following feedback. 11.<table> 12.<tr> 13.<td> 14.Name : 15.</td> 16.<td> 17.<bean:write name="feedbackForm" property="name" /> 18.</td> 19.</tr> 20.<tr> 21.<td> 22.Sex : 23.</td> 24.<td> 25.<logic:equal name="feedbackForm" property="sex" value="M"> Male </logic:equal> 26.<logic:equal name="feedbackForm" property="sex" value="F"> Female </logic:equal> 27.</td> 28.</tr> 29.<tr> 30.<td> 31.Comments : 32.</td> 33.<td> 34.<bean:write name="feedbackForm" property="comments" /> 35.</td> 36.</tr> 37.</table> 38.</body> 39.</html> On executing the example the following page will be dispalyed to the user.

Created by : Jignesh S. Prajapati

32

On submitting the feedback the following page will be dispalyed to the user.

You can download the source code of the Struts HTML Tags example by clicking on the Download link below.
Source :Download Source + Lib :Download

Created by : Jignesh S. Prajapati

33

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

Created by : Jignesh S. Prajapati

34

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

Created by : Jignesh S. Prajapati

35

<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.
Source :Download Source + Lib :Download

Created by : Jignesh S. Prajapati

Potrebbero piacerti anche