how to iterate Set in s:iterator in Struts 2 - struts2

I have a Set with list of objects, i want to iterate this set in s:iterator tag in struts 2 and access one of the property of Object.
How can i achieve this?
Sample code:
class Employee{
String name;
String age;
...getters and setters...
}
...
Set<Employee> empSet = new HashSet<Employee>;
empSet.add( ...some objects)
In Jsp: I want to access employee name
<s:iterator value = "empSet">
<property value=???(how to get employee name) >
</s:iterator>
Thanks

Iterator docs: http://struts.apache.org/2.1.6/docs/iterator.html
You want to do something like this:
<s:iterator value="empSet">
<p>Name is: <s:property value="name"/></p>
</s:iterator>
Note that you'll need a getter for empSet on your Action class.

Related

Formatting POJO inside Grails/GSP select element

I have the following POJO/POGO:
class Person {
String firstName
String lastName
int age
// ... lots of other fields
}
And a Grails 2.3.6 controller:
class PeopleController {
List<Person> people = new ArrayList<Person>()
def populatePeople() {
// Add lots of people to the 'people' list.
}
def doSomething() {
populatePeople()
render(
view: "people",
model:[
people: people,
]
)
}
}
And then in the GSP:
<div id="peopleSelector">
<g:select name="people" from="${people}" />
</div>
When I run my app I get the <select> element with com.me.myapp.domain.Person#398r4d99-looking values as <option>s. This is obviously Grails not deserializing my Person instances into pretty print form.
I want peoples' first and last names to appear as the select options. Hence, if one of the Person instances in the people list is:
Person smeeb = new Person(firstName: "Smeeb", lastNname: "McGuillocuty")
Then I would expect "Smeeb McGuillocuty" as a select option in the final HTML. How can I accomplish this?
Add the following method to your Person class:
#Override public String toString() {
"$firstName $lastName"
}
And, somewhat unrelated to the actual question, you may have to add an identifier to your option rows to uniquely identify the person. Assuming the Person class has an id property:
<g:select name="people" from="${people}" optionKey="id" />
so that you get the following HTML:
<select name="people" id="people">
<option value="123">Smeeb McGuillocuty</option>
:
Useful link to official doc: http://grails.org/doc/latest/ref/Tags/select.html:
"..The default behaviour is to call toString() on each element in the from attribute.."
If you can't/won't "sacrifice" toString() for rendering in HTML you can also tell the g:select how to render the options. Either by providing the name of a property in optionValue (e.g. optionValue="fullName" and then provide a String getFullName() method (watch out for transients, if you pass a GORM object)) or by providing it directly in the GSP:
<g:select name="person" optionKey="theId" optionValue='${{"$it.lastName, $it.firstName"}}' from="${people}" />

Struts 2 String to Double Conversion on ValueStack

I am new to Struts2 and following "Struts2 in Action". I have one question
My book says if you are using data-type different then String , you need to tell compiler that its no longer String and define property file named DataTransferTest-conversion.properties with Element-weights=java.lang.Double in case of List (i.e you are using Double type in your List).
However , when i did this practically , i didn't specified my property file. Still , its working. I don't know!! Why?
I am attaching my code layers. Please look
Action Class
public class ListExampleAction extends ActionSupport implements ModelDriven<ListExample> {
ListExample example = new ListExample();
private List<ListExample> listExample;
private Double x;
//Getters Setters//
#Action(value="/ListExample", results={
#Result(name="success",location="/listExampleDisplay.jsp"),
})
public String execute() throws Exception {
return "success";
}
Display Action Class( just to return jsp)
public class DisplayListExampleAction extends ActionSupport{
#Action(value="/ListExampleAction", results={
#Result(name="success",location="/listExample.jsp"),
})
public String execute() throws Exception {
return "success";
}
}
List Example Class for List Type
public class ListExample{
private String firstName;
private Double age;
//getter/setters//
}
listExample.jsp
<html>
<head></head>
<body>
<h1>Struts </h1>
<form action="ListExample">
// For List
<s:textfield name="listExample.firstName" label="User 1 Name"></s:textfield>
<s:textfield name="listExample.age" label="User 1 Age"></s:textfield>
// For x varaible in Action Class
<s:textfield name="x" label="x"></s:textfield>
<s:submit></s:submit>
</form>
</body>
</html>
listExampleDisplay.jsp
<html>
<head></head>
<body>
<h1>Struts</h1>
// For List
Users List =
<s:iterator value="listExample">
<s:property value="firstName" />
<s:property value="age" />
</s:iterator>
<br>
// For x varaible in Action Class
<s:property value="x"/>
</body>
</html>
Output:
UserAge =21
User Name = Saurabh
x = 21.0
Because the book is really old and covers only Struts 2.0.
Back then many types did require a conversion specification.
Later versions improved their ability to automatically convert between types through introspection.
IIRC that earlier book also didn't cover the annotations covered by some later books.

Get multiple values from strut2 iterator

I am new to struts. I dont know exactly if my solution for my problem is correct or not.
My problem is I have two tables as shown below
I would like to create an HTML table based on the above tables, showing the fields, name of group, id of group, and name of sub group and Id of subgroup. I tried to use list and iterator. But am not able to get both the values(both name and id)
inside class
public List getName() {
return namesHead;
}
public void setName(List name) {
this.namesHead = name;
}
public String listModules() {
SessionFactory factory = HibernateLoginUtil.getFactory();
Session session = factory.openSession();
Query q1 = session.createQuery ("select id,name FROM TableUsrModuleGroup WHERE stat='active'");
for(Iterator it = q1.iterate() ; it.hasNext() ;) {
Object row[] = (Object[]) it.next();
namesHead.add (row[1]); //put the name
}
return SUCCESS;
}
in JSP page
<table>
<s:iterator status="status" value="namesHead" >
<tr><td><s:property/></td></tr>
</s:iterator>
</table>
(only name of group can i get from the above code, I need to display group name, group Id, and name of sub group and Id of sub group)
If you are using Hibernate, I think that the simplest option is to map the two classes and then recover both with a HQL query. For instance:
public class Group {
#OneToMany (mappedBy = "group", fetch = FetchType.LAZY)
private Collection <SubGroup> subgroup;
... // Rest of the class, getters and setters
}
public class SubGroup {
#ManyToOne (fetch = FetchType.LAZY)
private Group group;
... // Rest of the class, getters and setters
}
Then you have to make this HQL query to get the Group class:
Query q = session.createQuery ("FROM SubGroup");
List<SubGroup> subgroups = (List<SubGroup>) q.list();
Then you set an attribute with the subgroups in the Action and then you access to them in the jsp.
<table>
<s:iterator value="subgroups" >
<tr>
<td>
<s:property value="name"/>
</td>
<td>
<s:property value="id"/>
</td>
<td>
<s:property value="group.name"/>
</td>
<td>
<s:property value="group.id"/>
</td>
</tr>
</s:iterator>
</table>
I hope it helps =)
Fetch object, not specific fields from database. You must have getter and setters for that object in your action, then in JSP you can get all properties of that object (don't forget setters/getters for object).

Struts2 Iterator property value (not working)

I am trying to use the struts iterator to write some data from a List. Student is a class I have defined.
The s:property when used with the value attribute does not seem to work at all.
I have the following code in the JSP:
<s:iterator value="students" var="student">
<h2><s:property /></h2>
<h2><s:property value="firstName" /></h2>
<h2><s:property value="student.firstName" /></h2>
<h2><s:property value="top.firstName" /></h2>
<h2><s:property value="[0].firstName" /></h2>
<h2><s:property value="#firstName" /></h2>
</s:iterator>
On the first property tag works. It prints the toString() of the Student object. All other property tags do not print anything at all.
The toString() method of Student class is as follows:
public String toString() {
return firstName + " " + lastName + " " + Integer.valueOf(age);
}
The Student class has the getFirstName() method as follows:
String getFirstName() {
return firstName;
}
I am using Struts 2.1.6
There are no exceptions in the log files.
When viewing source of html, I just see the empty h2 tags.
I wonder what is the issue here. Any help is appreciated.
Your getFirstName() method only has package-level access. It should be public to be accessible from the JSP.
change it to
public String getFirstName()
and you're set.
As you are using "var" attribute in iterator tag you have to refer the value from the object like
<s:iterator value="students" var="student">
<h2><s:property value="#student.firstName" /></h2>
</s:iterator>
You can write the same code without using var attribute like below
<s:iterator value="students">
<h2><s:property value="firstName" /></h2>
</s:iterator>
Both will works same.

Map multiple objects in to action class in struts2

I have jsp page with multiple item objects. and gives action to Shop_shopCart.action.
inside action class there are cart object with multiple item objects. How it is possible to directly mapping from jsp to action class with multiple list objects.
Demo classes are given below.
<s:form action="Shop_shopCart.action">
// multiple items in cart object
</form>
class ShoppingAction extends ActionSupport{
Cart cart = new Cart();
//getters and setters
//action methods
String shopCart( ) {
// do some
}
}
class Cart{
List<Item> items = new ArrayList<Item>();
//getters and setters
}
class Item{
String name;
int id;
//getters and setters
}
See the type conversion collection and map support docs.
Nutshell: array or map notation (square brackets with an index or key value inside them) is the easiest way to submit a collection of objects in a form.
this example should help
<s:form action="saveaction" theme="css_xhtml">
<s:textfield name="carlist[0].cartid" label="Cart Id"/>
<s:textfield name="carlist[0].items[0].id" label="Item id"/>
<s:textfield name="carlist[0].items[0].name" label="Item Name"/>
<s:textfield name="carlist[1].cartid" label="Cart Id"/>
<s:textfield name="carlist[1].items[0].id" label="Item id"/>
<s:textfield name="carlist[1].items[0].name" label="Item Name"/>
<s:submit value="Click me to submit Cart List"/>
</s:form>

Resources