davhab
davhab

Reputation: 805

Spring: Handle object with variable attributes

I have an object that has a dynamic number of attributes. For example a page that presents a car with all its details:

Now some privileged users can add attributes to the car object. Let's say at some point the requirement arises that any user should be able to specify the lenght of the car, so we would like to add a new attribute

I have gotten to the point where I have the form for creating new cars that shows all fields including the additionally added ones:

    <!-- ADDITIONAL ATTRIBUTES -->

    <c:forEach items="${attributes}" var="a">

    <div class="${a}">
        <span class="details_headline">${a}:</span>
        <input id="${a}" name="${a}" class="input" type="text" value="" placeholder="${a}"/>
    </div>

    </c:forEach>

    <!-- END ADDITIONAL ATTRIBUTES -->

How can I now pass all these attributes to the controller that will then add the new car to my system?

I believe the structure that I am looking for is a map containing the attribute as keys and the respective values which could then be further processed by the controller. How can I achieve this?

Thanks!

Upvotes: 1

Views: 343

Answers (1)

marco.eig
marco.eig

Reputation: 4239

i assume you are using spring mvc?

you might want to create a simple model bean like this

public class AttributesBean {
    private Map<String, String> attributes = new HashMap<String,String>();

    // omitted getters and setters
}

you can now pass the attributes values to this bean => attributes[${a}] (assuming that 'a' is a enum, String or other primitive type (consider using ConversionService API if you want to use a more complex type as the key))

<!-- ADDITIONAL ATTRIBUTES -->

<c:forEach items="${attributes}" var="a">

<div class="${a}">
    <span class="details_headline">${a}:</span>
    <input id="${a}" name="attributes[${a}]" class="input" type="text" value="" placeholder="${a}"/>
</div>

</c:forEach>

<!-- END ADDITIONAL ATTRIBUTES -->

Spring will create a new AttributesBean object and will bind these parameters to the corresponding fields.

@RequestMapping
public void handleAttributes(final AttributesBean bean) {
    // bean.getAttributes().get("abc");
}

i couldn't try it, but it should work actually

Upvotes: 1

Related Questions