Pages

Monday, November 12, 2012

Post List of objects from jsp to Struts action

from: http://birenj2ee.blogspot.ca/2011/03/post-list-of-objects-from-jsp-to-struts.html
How to pass objects list from jsp to Struts?
How to post objects list from jsp to Struts?
Struts 2 framework have provided very powerful features using OGNL to post list of Objects from jsp to Struts 2 Action class.

Here is the example of passing list of objects from jsp to Struts.

We must have Struts 2 framework with OGNL script.
Following example will allows you to add multiple user list at the same time from jsp.
Code of required POJO, Acion Class and Jsp to post list of Person Object from jsp to action class are written below.

Person.Java Pojo

  1. public class Person   
  2. {      
  3.     int person_id;  
  4.     String name;  
  5.     String address;  
  6.     public int getPerson_id() {  
  7.         return person_id;  
  8.     }  
  9.     public void setPerson_id(int personId) {  
  10.         person_id = personId;  
  11.     }  
  12.     public String getName() {  
  13.         return name;  
  14.     }  
  15.     public void setName(String name) {  
  16.         this.name = name;  
  17.     }  
  18.     public String getAddress() {  
  19.         return address;  
  20.     }  
  21.     public void setAddress(String address) {  
  22.         this.address = address;  
  23.     }  
  24. }  
Struts 2 Action Class
  1. @ParentPackage("default")  
  2. public class ManageUsers extends ActionSupport    
  3. {  
  4.     List<Person> personList ;  
  5.     @Action(value="addUserList",results={  
  6.             @Result(name=ActionSupport.SUCCESS,location="addPersonList",type="tiles")})  
  7.     public String execute() throws Exception  
  8.     {        
  9.         if(personList==null)  
  10.         {           
  11.             personList = new ArrayList<Person>();  
  12.         }        
  13.         Person p = new Person();  
  14.         p.setName("NAME");  
  15.         personList.add(p);        
  16.         return SUCCESS;  
  17.     }  
  18.     public List<Person> getPersonList() {  
  19.         return personList;  
  20.     }  
  21.     public void setPersonList(List<Person> personList) {  
  22.         this.personList = personList;  
  23.     }  
  24. }  
JSP

  1. <s:if test="personList != null && personList.size > 0">  
  2.         <tr>  
  3.             <th width="50%">Person Name</th>  
  4.             <th width="50%">Address</th>  
  5.         </tr>  
  6.     <s:iterator value="personList"  status="p">  
  7.         <tr>  
  8.             <td><s:textfield name="personList[%{#p.index}].name" /></td>  
  9.              <td><s:textfield name="personList[%{#p.index}].address" /></td>  
  10.         </tr>  
  11.     </s:iterator>  
  12.     </s:if>  





find more on http://sunfeng.ca/

1 comment: