EdgeCase
EdgeCase

Reputation: 4827

Spring MVC - Submit an Object from JSP

I have a JSP that presents a list of customers (ArrayList searchResults). I want to be able to pick one of those, and submit it to a Spring MVC controller. However, it appears that I cannot pass the selected object, only a property of it, such as customerId. I really need to pass the entire object.

Is there a standard way to do this in Spring 3.x?

<c:forEach items="${searchResults}" var="searchResult">
    <tr>
        <td><c:out value="${searchResult.customerId}" /></td>
        <td><c:out value="${searchResult.firstName}" /></td>
        <td><c:out value="${searchResult.lastName}" /></td>
        <td>
            <form method="POST" ACTION="./customercare">
                <input type="SUBMIT" value="Select This Customer"/>
                <input type="hidden" name ="searchResult" value="${searchResult}"/>
            </form>
        </td>
    </tr>
</c:forEach>

Upvotes: 2

Views: 8727

Answers (3)

Bruce Lowe
Bruce Lowe

Reputation: 6203

You could have 1 form per customer with a lot of hidden inputs in. When that customer is selected you can POST that form. Spring can then bind all the hidden inputs to your customer object.

(Generally, I would just send the id only and load the customer info, as an entity, from a Database. However, I assume you must have a good reason for not wanting to do this)

Upvotes: 0

Vikram
Vikram

Reputation: 4190

You might want to consider giving id to each and nested tags to differentiate between row that you want to POST

<c:forEach items="${searchResults}" var="searchResult">
    <tr> 
....
            <form:form id="${searchResults.key}-form" method="POST" ACTION="./customercare">
                <form:input id="${searchResults.key}-btn" type="SUBMIT" value="Select This Customer"/>
                <form:input id="${searchResults.key}-hidden" type="hidden" name ="${searchResults.key}" value="searchResult['${searchResults.key}']"/>
            </form:form>

    </tr>

On the backend side you will have to write the controller as suggested by @PatBurke

Upvotes: 0

Pat Burke
Pat Burke

Reputation: 590

You can use Spring's form taglib instead of plain <form> to post back to a Spring MVC Controller and then it will Bind the values back to the model you specify.

<form:form method="post" action="addContact.html">

<table>
<tr>
    <td><form:label path="firstname">First Name</form:label></td>
    <td><form:input path="firstname" /></td> 
</tr>

...

@RequestMapping(value = "/addContact", method = RequestMethod.POST)
public String addContact(@ModelAttribute("contact")
                        Contact contact, BindingResult result) {

See this Post: http://viralpatel.net/blogs/spring-3-mvc-handling-forms/

Upvotes: 4

Related Questions