I am using Struts2. Please help me in understanding how to retrieve the elements of HashSet
using Struts2 tag without using Struts iterator tag.
struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package name="bundle" extends="struts-default" namespace="/">
<action name="fetchPage">
<interceptor-ref name="defaultStack" />
<result name="success">/jsp/page.jsp</result>
</action>
<action name="process"
class="sample.action.Process"
method="execute">
<interceptor-ref name="defaultStack" />
<result name="success">/jsp/result.jsp</result>
</action>
</package>
</struts>
Process.java (Action Class)
package sample.action;
import java.util.HashSet;
import java.util.Set;
import sample.pojo.Customer;
import com.opensymphony.xwork2.ActionSupport;
public class Process extends ActionSupport
{
private Set<Customer> result = new HashSet<Customer>();
public String execute()
{
Customer cust1 = new Customer();
cust1.setAge(59);
cust1.setName("Subramanian");
result.add(cust1);
return SUCCESS;
}
public Set<Customer> getResult() {
return result;
}
public void setResult(Set<Customer> result) {
this.result = result;
}
}
Cutomer.java - Pojo class
package sample.pojo;
public class Customer{
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
result.jsp - View
<!DOCTYPE html>
<html>
<head>
<%@ taglib prefix="s" uri="/struts-tags"%>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=8;" />
<title>Welcome Page</title>
</head>
<body>
Welcome!
<s:textfield id="custName" value="%{result[0].name}"/>
</body>
</html>
With above code, I am not able to read HashSet
object value in result.jsp
page.
How to retrieve the elements of
HashSet
using Struts2 tag without using<s:iterator>
?By using some OGNL magic called projection.
The
result.{name}
will create a list from allname
values in theresult
and the[0]
will retrieve first element of that list.Note that because you are using
HashSet
iteration order is not guaranteed. UseLinkedHashSet
to achieve predictable iteration order.