Pages Navigation Menu

Coding is much easier than you think

Dynamically add, remove list of objects from jsp Using Struts2

Dynamically add, remove list of objects from jsp Using Struts2

In this article we shall learn on how to dynamically add, remove list of objects from jsp Using Struts2.
File : (Model Class)

package com.simplecode.action;

import java.util.Collection;

public class User 
	int regNo;
	String name;
	Collection<Address> addresses;

	public Collection<Address> getAddresses() 
		return addresses;

	public void setAddresses(Collection<Address> addresses) 
		this.addresses = addresses;

	public int getRegNo() 
		return regNo;

	public void setRegNo(int regNo) 
		this.regNo = regNo;

	public String getName() 
		return name;

	public void setName(String name) 
	{ = name;

File : Bean Class

package com.simplecode.action;

public class Address 
	private int houseNo;
	private String street;
	private String city;
	private String country;

	public int getHouseNo() 
		return houseNo;

	public String getStreet() 
		return street;

	public void setHouseNo(int houseNo) 
		this.houseNo = houseNo;

	public void setStreet(String street) 
		this.street = street;

	public String getCountry() 
		return country;

	public void setCountry(String country) 
	{ = country;

	public String getCity() 
		return city;

	public void setCity(String city) 
	{ = city;

In order to implement the above functionality via ajax, do read the article on CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax
Do read :

 File : UserAction (Action Class)

package com.simplecode.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction implements Action, ModelDriven<User> 
	User user = new User();
	public User getUser() 
		return user;
	public void setUser(User user) 
		this.user = user;
	public String execute() 
		return SUCCESS;
	public User getModel() 
		return user;

In the above article I have used the concept of ModelDriven interface in struts2, if you are not aware of what model driven interface is, then please read the article on modeldriven interface here

Jsp Pages

File : index.jsp

<title>Add/Remove dynamic rows</title>
<SCRIPT lang="javascript">
	function addRow(tableID) 
		var table = document.getElementById(tableID);

		var rowCount = table.rows.length;
		var row = table.insertRow(rowCount);
		var counts = rowCount - 1;

		var cell1 = row.insertCell(0);
		var houseNo = document.createElement("input");
		houseNo.type = "text"; = "addresses[" + counts + "].houseNo";

		var cell2 = row.insertCell(1);
		var street = document.createElement("input");
		street.type = "text"; = "addresses[" + counts + "].street";

		var cell3 = row.insertCell(2);
		var city = document.createElement("input");
		city.type = "text"; = "addresses[" + counts + "].city";

		var cell4 = row.insertCell(3);
		var country = document.createElement("input");
		country.type = "text"; = "addresses[" + counts + "].country";


<form action="submit" method="post">
Reg No  
<td><INPUT type="text" name="regNo" /></td>
<td><INPUT type="text" name="name" /></td>


<TABLE id="addressesTable">
		<TD>House No</TD>
		<TD><INPUT type="text" name="addresses[0].houseNo" /></TD>
		<TD><INPUT type="text" name="addresses[0].street" /></TD>
		<TD><INPUT type="text" name="addresses[0].city" /></TD>
		<TD><INPUT type="text" name="addresses[0].country" /></TD>
<INPUT type="button" value="Add More" onclick="addRow('addressesTable')" /> 
<input type="submit" value="SUBMIT" />

File : result.jsp

<%@taglib prefix="s" uri="/struts-tags"%>
<title>User Details</title>
	<h1>User information</h1>
	ID : <s:property value="regNo" /><br /> 
	Name : <s:property value="name" /><br /> 
	Addresses :
    <td width="10%">Reg No :</td>
    <td width="15%" >Street :</td>
    <td width="15%" >City :</td>
    <td width="15%">Country :</td>

<s:iterator value="addresses">
    <td width="10%"><s:property value="houseNo" /></td>
    <td width="15%" ><s:property value="street"/></td>
    <td width="15%" ><s:property value="city"/></td>
    <td width="15%"><s:property value="country"/></td>

Recommended reading :




<?xml version="1.0" encoding="UTF-8" ?>
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

    <package name="default" extends="struts-default">
        <action name="submit" class="com.simplecode.action.UserAction">
            <result name="success">result.jsp</result>


Run it

On running the application
Collection values
Input collection
Collection output
** UPDATE: Struts 2 Complete tutorial now available here.

About Mohaideen Jamil

Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

  • انتن نور شافينز

    or may i only get part of auto complete multiple field in jsp as in invoice system . i really need it , this is my interface, but i just want to know the process of auto complete based on values that already registered in my DB,

  • انتن نور شافينز

    excuse me, may I ask something, i already got the source code from gmail, but then, can I convert this code into jsp, or you have another source code abt invoice in jsp files , please help me :(

  • Samila Salam

    can u include the database inserstion of this form???
    plsese help its urgent .i stuck on this

  • Samila Salam

    i want add button along with each row.when i click button in row add one row below.
    how can do this ? help me

  • Sharad Khomane

    how to write code for update and delete opeation in struts 2 …. thank u sir

  • gobisankar

    please also provide dynamically delete row

  • sri

    i have list of objects such as id,name and salary and this list is appended to a combo box which is returned from a action, when i select a option name from the combo i should get salary of particular value. Can i do this using struts

  • jeeten

    great work thank you sir for the help

  • Jassi

    I am working on struts2 application. From a jsp seereports.jsp that contains a form. On submit action is called and i want to return on same jsp and action returns a list and i want to iterate the list on the same jsp. Is that possible without making ajax call. Its returning to seereports.jsp but no data is displayed even after writing the iterate code. Please help.

    • Mohaideen Jamil

      Yes it is possible

  • Ayush Mathur

    Hi Jamil,
    I have a requirement to create a user menu in tree structure (say root, level1, level2, level3) on left panel of browser and their content should be displayed on right upon clicking them.
    Now under the level2 node, I need to create sub-menus by taking sub-menu name as input from the user. Can you please guide me to achieve this functionality ?

  • Chirag

    Can you plz upload the war or zip file as i m getting an error or mail me …thanks in advance :)

  • Vishnu

    Hi jamil,
    In my jsp page is not working for dynamic generated rows..And not adding values from dynamic rows to multiple rows into me

  • Vishnu

    i am facing an error
    Exception starting filter struts2
    java.lang.UnsupportedClassVersionError: Bad version number in .class file (unable to load class com.simplecode.action.UserAction)

    • Vishnu

      i am using jdk1.7 and its compiling with out any problem while starting the server i got the error

    • Vishnu


      • Mohaideen Jamil

        Glad that it worked :)

  • Vishnu

    Hi ,
    How to write code for ModelDriven and Action

  • Michael

    How would you also dynamically add the name of the textbox over? Like along side the textbox or above it?

  • Madhuri

    hi, I am also working on dynamically adding table row using jsp, but i am getting one exception in that : whenever in a table there is only one row and i submit, it trough’s an error , but works fine when i add row that means when there’s total 2 row in a table.
    can anybody help me resolve this issue …

  • Aamin Khan

    First Thank you…its working for me…Now I want to iterate the collection on server side. I already did a bit, but the problem is when i delete a element the collection display before to the elements i delete.. please help me up..

  • Abdelnabi Yousfi

    I had the same need (add a row in the jsp and after submitting, add the element to a list), I thought of the same solution (renaming the fields added), but I got a nullpointerexception when I try to dispay the elements of my collection… For example, in your case, you would have a nullpointerexception in the following line:
    for(Adresse a: user.getAdresses()) System.out.println(a.getStreet());…

    Any idea about what I’m doing wrong please?


    • Mohaideen Jamil

      Hi Yousfi,

      Code works fine.. the thing if you have used any string inside list element, and if you have not not entered any values in jsp, then it will obviously leads to NullPointer exception, you just need to handle the same in java side.

  • Garay

    Muchas Gracias! :)

    • Jamil

      Spanish Translated – Thank you very much :)

      – You are welcome :)