Struts 2 generator tag is used to generate an iterator based on the “val” attribute provided in the page. In this tutorials, you will use Struts 2 generator tag to do the following tasks :

  1. Create an iterator with generator tag.
  2. Create an iterator with generator tag and modify the iterator value with the “Converter” object.

1. Action

An Action class with a method which return an “Converter” object.

GeneratorTagAction

package com.mkyong.common.action;
 
import org.apache.struts2.util.IteratorGenerator.Converter;
import com.opensymphony.xwork2.ActionSupport;
 
public class GeneratorTagAction extends ActionSupport{
 
	public String execute() {
 
		return SUCCESS;
	}
 
	public Converter getLanguageConverter(){
		return new Converter() {
	         public Object convert(String value) throws Exception {
 
	        	 if("java".equals(value)){
	        		 return "[java value in converter] - " + value;
	        	 }else{
	        		 return value;
	        	 }
 
	         }
	     };
	}
}

2. Generator tag example

A JSP page to show the use of generator tag to create a iterator dynamically. The “separator” attribute is required, which separating the val into the entries of the iterator.

The “converter” attribute is optional, which allow you to modify the value. In this case, it will call the GeneratorTagAction’s getLanguageConverter() method, and modify the value if the value is equal to “java” string.

generator.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
 <html>
<head>
</head>
 
<body>
<h1>Struts 2 Generator tag example</h1>
 
1. Generator tag example.
<s:generator val="%{'java|.net|c|python|shell'}" separator="|">
<ol>
<s:iterator>
  <li><s:property /></li>
</s:iterator>
</s:generator>
</ol>  
 
2. Generator tag with converter example
<s:generator val="%{'java|.net|c|python|shell'}" separator="|" 
converter="%{languageConverter}">
<ol>
<s:iterator>
  <li><s:property /></li>
</s:iterator>
</s:generator>
</ol>  
 
</body>
</html>
Can’t find any use case of this generator tag, as i don’t recommend to hardcore the iterator values in the page.

3. struts.xml

Link it ~

<?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="default" namespace="/" extends="struts-default">
 
		<action name="appendTagAction" 
			class="com.mkyong.common.action.AppendTagAction" >
			<result name="success">pages/appendIterator.jsp</result>
		</action>
 
	</package>
 
</struts>

4. Demo

http://localhost:8080/Struts2Example/generatorTagAction.action

Struts 2 generator tag

Reference

  1. Struts 2 Generator documentation
  2. Struts 2 Converter documentation
Note : You can find more similar articles at - Struts 2.x Tutorials