The Struts 2 tags has a set of tags that makes it easy to control the flow of page execution.
Following is the list of important Struts 2 Control Tags: The If and Else Tags These tags perform basic condition flow found in every language. 'If' tag is used by itself or with 'Else If' Tag and/or single/multiple 'Else' Tag as shown below:
<s:if test="%{false}">
<div>Will Not Be Executed</div> </s:if> <s:elseif test="%{true}"> <div>Will Be Executed</div> </s:elseif> <s:else> <div>Will Not Be Executed</div> </s:else> If and Else Tags – Detailed Example Create Action Class
package com.jtc.struts2;
public class HelloWorldAction{ private String name; public String execute() throws Exception { return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Create views Let us have index.jsp file as follows:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello World From Struts2</h1> <form action="hello"> <label for="name">Please pick a name</label><br/> <select name="name"> <option name="Mike">Mike</option> <option name="Jason">Jason</option> <option name="Mark">Mark</option> </select> <input type="submit" value="Say Hello"/> </form> </body> </html> Next let us have HelloWorld.jsp to demonstrate the use of the if, else and elseif tags:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Example of If and Else</title> </head> <body> <b>Example of If and Else</b><br/> <s:if test="name=='Mike'"> You have selected 'Mike'. </s:if> <s:elseif test="name=='Jason'"> You have selected 'Jason' </s:elseif> <s:else> You have not selected 'Mike' or 'Jason'. </s:else> </body> </html> Here, the “if” tag returns true if the condition specified in the "test" attribute returns true. In our case, we are comparing it against "Mike". If the name is Mike, the tag returns true and we print the string, otherwise the "elseif" block gets executed and if that is not satisfied, then the else block gets executed. This is no different from the conventional if, else if and else available in the Java language. Configuration Files Your struts.xml should look like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="helloworld" extends="struts-default"> <action name="hello" class="com.jtc.struts2.HelloWorldAction" method="execute"> <result name="success">/HelloWorld.jsp</result> </action> </package> </struts> Your web.xml should look like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen: Now select "Mark" and submit the page. You should see the next page. The Iterator Tags This iterator will iterate over a value. An iterable value can be either itherjava.util.Collection or java.util.Iterator file. While iterating over an iterator, you can use Sort tag to sort the result or SubSet tag to get a sub set of the list or array. The following example retrieves the value of the getDays() method of the current object on the value stack and uses it to iterate over. The <s:property/> tag prints out the current value of the iterator.
<s:iterator value="days">
<p>day is: <s:property/> </s:iterator> The Iterator Tags – Detailed Example Create Action Classes First of all let us create a simple class called Employee.java which looks like:
package com.jtc.struts2;
import java.util.ArrayList; import java.util.List; import org.apache.struts2.util.SubsetIteratorFilter.Decider; public class Employee { private String name; private String department; public Employee(){} public Employee(String name,String department) { this.name = name; this.department = department; } private List employees; private List contractors; public String execute() { employees = new ArrayList(); employees.add(new Employee("George","Recruitment")); employees.add(new Employee("Danielle","Accounts")); employees.add(new Employee("Melissa","Recruitment")); employees.add(new Employee("Rose","Accounts")); contractors = new ArrayList(); contractors.add(new Employee("Mindy","Database")); contractors.add(new Employee("Vanessa","Network")); return "success"; } public Decider getRecruitmentDecider() { return new Decider() { public boolean decide(Object element) throws Exception { Employee employee = (Employee)element; return employee.getDepartment().equals("Recruitment"); } }; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public List getEmployees() { return employees; } public void setEmployees(List employees) { this.employees = employees; } public List getContractors() { return contractors; } public void setContractors(List contractors) { this.contractors = contractors; } } The Employee class has two attributes - name and department, we also have two lists of employees - the permanent employees and the contractors. We have a method called getRecruitmentDeciderthat returns a Decider object. The Decider implementation returns true if the employee works for the recruitment department, and it returns false otherwise. Next, let us create a DepartmentComparator to compare Employee objects:
package com.jtc.struts2;
import java.util.Comparator; public class DepartmentComparator implements Comparator { public int compare(Employee e1, Employee e2) { return e1.getDepartment().compareTo(e2.getDepartment()); } @Override public int compare(Object arg0, Object arg1) { return 0; } } As shown in the above example, the department comparator compares the employees based on the department in alphabetical order. Create Views Create a file called employee.jsp with the following contents:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Employees</title> </head> <body> <b>Example of Iterator Tag</b><br/> <s:iterator value="employees"> <s:property value="name"/> , <s:property value="department"/><br/> </s:iterator> <br/><br/> <b>Employees sorted by Department</b><br/> <s:bean name="com.jtc.struts2.DepartmentComparator" var="deptComparator" /> <s:sort comparator="deptComparator" source="employees"> <s:iterator> <s:property value="name"/> , <s:property value="department"/><br/> </s:iterator> </s:sort> <br/><br/> <b>SubSet Tag - Employees working in Recruitment department </b><br/> <s:subset decider="recruitmentDecider" source="employees"> <s:iterator> <s:property value="name"/> , <s:property value="department"/><br/> </s:iterator> </s:subset> <br/><br/> <b>SubSet Tag - Employees 2 and 3 </b><br/> <s:subset start="1" count="2" source="employees"> <s:iterator> <s:property value="name"/> , <s:property value="department"/><br/> </s:iterator> </s:subset> </body> </html> Let us go through the used tags one by one: Iterator Tag We are using the iterator tag to go through the employees list. We supply the "employees" property as the source to the iterator tag. In the body of the iterator tag, we now have access to the Employee object in the employees list. We print the name of the employee followed by their department. Sort Tag First of all we declared the DepartmentComparator as a bean. We gave this bean a name deptComparator. Then we used the sort tag and specify the "employees" list as the source and the "deptComparator" as the comparator to use. Then, as per the previous example, we iterate the list and print the employees. As you can see from the output, this prints the list of employees sorted by department Subset Tag The subset tag is used to get a sub set of the list or array. We have two flavors of subset tag. In the first example, we use the recrutimentDecider to get the list of employees who work for the recruitment department (please see the getRecruitmentDecider() method in Employee.java). In the second example, we are not using any deciders but instead we are after elements 2 and 3 in the list. The subset tag takes in two parameters "count" and "start". "start" determines the starting point of the subset and the "count" determines the length of the subset. Configuration Files Your struts.xml should look like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="helloworld" extends="struts-default"> <action name="employee" class="com.jtc.struts2.Employee" method="execute"> <result name="success">/employee.jsp</result> </action> </package> </struts> Your web.xml should look like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/employee.action. This will produce the following screen: The Merge Tag These merge tag takes two or more lists as parameters and merge them all together as shown below:
<s:merge var="myMergedIterator">
<s:param value="%{myList1}" /> <s:param value="%{myList2}" /> <s:param value="%{myList3}" /> </s:merge> <s:iterator value="%{#myMergedIterator}"> <s:property /> </s:iterator> The Merge Tag – Detailed Example Say if you have two lists A and B with values A1,A2 and B1,B2. Merging the lists will give you A1,B1,A2,B2. Create Action Classes First of all let us create a simple class called Employee.java which looks like:
package com.jtc.struts2;
import java.util.ArrayList; import java.util.List; import org.apache.struts2.util.SubsetIteratorFilter.Decider; public class Employee { private String name; private String department; public Employee(){} public Employee(String name,String department) { this.name = name; this.department = department; } private List employees; private List contractors; public String execute() { employees = new ArrayList(); employees.add(new Employee("George","Recruitment")); employees.add(new Employee("Danielle","Accounts")); employees.add(new Employee("Melissa","Recruitment")); employees.add(new Employee("Rose","Accounts")); contractors = new ArrayList(); contractors.add(new Employee("Mindy","Database")); contractors.add(new Employee("Vanessa","Network")); return "success"; } public Decider getRecruitmentDecider() { return new Decider() { public boolean decide(Object element) throws Exception { Employee employee = (Employee)element; return employee.getDepartment().equals("Recruitment"); } }; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public List getEmployees() { return employees; } public void setEmployees(List employees) { this.employees = employees; } public List getContractors() { return contractors; } public void setContractors(List contractors) { this.contractors = contractors; } } The Employee class has two attributes - name and department, we also have two lists of employees - the permanent employees and the contractors. We have a method called getRecruitmentDecider that returns a Decider object. The Decider implementation returns true if the employee works for the recruitment department, and it returns false otherwise. Next, let us create a DepartmentComparator to compare Employee objects:
package com.jtc.struts2;
import java.util.Comparator; public class DepartmentComparator implements Comparator { public int compare(Employee e1, Employee e2) { return e1.getDepartment().compareTo(e2.getDepartment()); } @Override public int compare(Object arg0, Object arg1) { return 0; } } As shown in the above example, the department comparator compares the employees based on the department in alphabetical order. Create Views Create a file called employee.jsp with the following contents:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Employees</title> </head> <body> <b>Employees and Contractors Merged together</b> <br /> <s:merge id="allemployees"> <s:param value="employees" /> <s:param value="contractors" /> </s:merge> <s:iterator value="allemployees"> <s:property value="name"/>, <s:property value="department"/><br/> </s:iterator> </body> The merge tag takes two or more lists as parameters. We need to give the merge an id so that we can reuse it later. In this example, we supply employees and contractors as parameters to the merge tag. We then use the "allemployees" id to iterate through the merged list and print the employee details. Configuration Files Your struts.xml should look like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="helloworld" extends="struts-default"> <action name="employee" class="com.jtc.struts2.Employee" method="execute"> <result name="success">/employee.jsp</result> </action> </package> </struts> Yourweb.xml should look like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/employee.action. This will produce the following screen: The Append Tag These append tag take two or more lists as parameters and append them all together as shown below:
<s:append var="myAppendIterator">
<s:param value="%{myList1}" /> <s:param value="%{myList2}" /> <s:param value="%{myList3}" /> </s:append> <s:iterator value="%{#myAppendIterator}"> <s:property /> </s:iterator> The Append Tag – Detailed Example Say if you have two lists A and B with values A1,A2 and B1,B2. Merging the lists will give you A1,B1,A2,B2 whereas appending the lists will give you A1,A2,B1,B2. Create action classes First of all let us create a simple class called Employee.java which looks like:
package com.jtc.struts2;
import java.util.ArrayList; import java.util.List; import org.apache.struts2.util.SubsetIteratorFilter.Decider; public class Employee { private String name; private String department; public Employee(){} public Employee(String name,String department) { this.name = name; this.department = department; } private List employees; private List contractors; public String execute() { employees = new ArrayList(); employees.add(new Employee("George","Recruitment")); employees.add(new Employee("Danielle","Accounts")); employees.add(new Employee("Melissa","Recruitment")); employees.add(new Employee("Rose","Accounts")); contractors = new ArrayList(); contractors.add(new Employee("Mindy","Database")); contractors.add(new Employee("Vanessa","Network")); return "success"; } public Decider getRecruitmentDecider() { return new Decider() { public boolean decide(Object element) throws Exception { Employee employee = (Employee)element; return employee.getDepartment().equals("Recruitment"); } }; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public List getEmployees() { return employees; } public void setEmployees(List employees) { this.employees = employees; } public List getContractors() { return contractors; } public void setContractors(List contractors) { this.contractors = contractors; } } The Employee class has two attributes - name and department, we also have two lists of employees - the permanent employees and the contractors. We have a method called getRecruitmentDecider that returns a Decider object. The Decider implementation returns true if the employee works for the recruitment department, and it returns false otherwise. Next, let us create a DepartmentComparator to compare Employee objects:
package com.jtc.struts2;
import java.util.Comparator; public class DepartmentComparator implements Comparator { public int compare(Employee e1, Employee e2) { return e1.getDepartment().compareTo(e2.getDepartment()); } @Override public int compare(Object arg0, Object arg1) { return 0; } } As shown in the above example, the department manager compares the employees based on the department in alphabetical order. Create Views Creates a file called employee.jsp with the following contents:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Employees</title> </head> <body> <b>Employees and Contractors Merged together</b> <br /> <s:append id="allemployees"> <s:param value="employees" /> <s:param value="contractors" /> </s:append > <s:iterator value="allemployees"> <s:property value="name"/>, <s:property value="department"/><br/> </s:iterator> </body> </html> The append tag takes two or more lists as parameters. We need to give the append an id so that we can reuse it later. In this example, we supply employees and contractors as parameters to the append tag. We then use the "allemployees" id to iterate through the appended list and print the employee details. Configuration Files Your struts.xml should look like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="helloworld" extends="struts-default"> <action name="employee" class="com.jtc.struts2.Employee" method="execute"> <result name="success">/employee.jsp</result> </action> </package> </struts> Your web.xml should look like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/employee.action. This will produce the following screen: The Generator Tag These generator tag generates an iterator based on the val attribute supplied. The following generator tag generates an iterator and prints it out using the iterator tag.
<s:generator val="%{'aaa,bbb,ccc,ddd,eee'}">
<s:iterator> <s:property /><br/> </s:iterator> </s:generator> The Generator Tag – Detailed Example Often we come across situation where we have to create a list or array on the fly and iterate through the list. You could create the list or array using scriptlets or you can use the generator tag. Create Action Class
package com.jtc.struts2;
public class HelloWorldAction{ private String name; public String execute() throws Exception { return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Create Views Let us have HelloWorld.jsp to demonstrate the use of the generator tag:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Hello World</title> </head> <body> <h2>Example of Generator Tag</h2> <h3>The colours of rainbow:</h3> <s:generator val="%{'Violet,Indigo,Blue, Green,Yellow,Orange,Red '}" count="7" separator=","> <s:iterator> <s:property /><br/> </s:iterator> </s:generator> </body> </html> Here we are creating a generator tag and we ask it to parse the string that contains comma separated list of colors that form a rainbow. We tell the generator tag that the separator is "," and we want all seven values in the list. If we are only interested in the first three values, then we would set the count to 3. In the body of the generator tag, we used the iterator to go through the values created by the generator tag and we print the value of the property. Configuration Files Your struts.xml should look like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="helloworld" extends="struts-default"> <action name="hello" class="com.jtc.struts2.HelloWorldAction" method="execute"> <result name="success">/HelloWorld.jsp</result> </action> </package> </struts> Your web.xml should look like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/hello.action. This will produce the following screen: |