Announcement Announcement Module
Collapse
No announcement yet.
Binding To A List Of Object On A Form Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Binding To A List Of Object On A Form

    I'm a Spring (and JSP) newbie, so please be kind. Let's say I have a Product class that contains a collection of three Option classes.

    Product = Shirt
    Options = Color {red, blue, green}, Size {small, medium, large}, Sleeve {short, long}

    How can I loop through each Option within a Product and display them in a form so I get each option's selected value when submitted? I'm guessing I need to use an index in the path attribute, I just don't know how to do this.

    Code:
    public class Product {
        
        private String name;
        private List<Option> options;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public List getOptions() {
            return options;
        }
    
        public void setOptions(List options) {
            this.options = options;
        }
    
    }
    Code:
    public class Option {
        
        private String name;
        private String value;
        private String[] possibleValues;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    	
        public String getValue() {
            return value;
        }
    
        public void setValue(String value) {
            this.value = value;
        }
    
        public String[] getPossibleValues() {
            return possibleValues;
        }
    
        public void setPossibleValues(String[] possibleValues) {
            this.possibleValues = possibleValues;
        }
    
    }
    Code:
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <title>Product</title>
        </head>
        <body>
            <form:form method="post" commandName="product">
               <c:out value="Product: ${name}"/>
    	    <c:forEach var="option" items="${options}">
    	        <c:out value="Option: ${name}"/>
    	        <form:select path="${value}" items="${possibleValues}"/>
    	        <br>
    	    </c:forEach>
               <input type="submit" value="Submit"/>
            </form:form>
        </body>
    </html>
Working...
X