Saturday, March 14, 2009

Array Binding In Spring

Sending data from JSP to controller in easy no matter whether it is string, integer or an array. Problem occurs in displaying JSP page if the data in present in command class and it is an array.
Following is sample JSP code to bind an array of names to the command class in spring. The code will both send and display the data.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="core" uri="http://java.sun.com/jstl/core" %>
<html>
<head>
<title>Test</title>
</head>
<body>
<form:form commandName="test" method="post" action="welcome.do" >
    <core:set var="flag" value="false" />
<!-- Create the n number of name fields if data is present -->
    <core:forEach items="${test.name}" var="n" varStatus="status">
        <form:input path="name[${status.index}]"  />
        <core:set var="flag" value="true" />
    </core:forEach>
<!-- If data is not present then create 2(default) name fields -->
    <core:if test="${flag eq false}">
            <form:input path="name"  />
            <form:input path="name"  />
    </core:if>
    <input type="submit" value="submit" />
</form:form>
</body>
</html>


In the above example String[] name; is used in the command class.
That All !!! :)