0

Today I am stuck with the spring-form with the POST method which doesn't give posted item to the Controller which I wanted. Here is my code.

Controller.java

@Controller
@RequestMapping("/cart")
public class CartController extends CommonController
{
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ModelAndView addCart(@ModelAttribute("productList") Item item, BindingResult result,Model model){
         System.out.println(item.getId()); /// <-- doesn't gives me the ID
         return new ModelAndView("cart");
    }
 }

ProductList.jsp

/// Loop through the products of search itemlist and generates the forms with the correct items
<c:forEach var="item" items="${productList.items}" varStatus="status">
                    ${item.name}
        <div class="addCart">
        <c:url value="/cart/add.html" var="addURL" />
            <form:form method="POST" action="${addURL}" modelAttribute="productList">
                <form:hidden path="items[${status.index}].id"/>
                <input type="submit" class="addCartBtn" value="Add to cart" />
            </form:form>
        </div>

BackingBean.java

public class SearchForm implements Serializable
{
   private Collection<Item> items;
   private String term;
   // getters and setters
}

The ${productList} is the backingbean which loops through all items.

I don't really know what the problem is why it isn't giving me the correct data it passed through the POST. Many thanks.

Skyverian
  • 53
  • 1
  • 1
  • 7

1 Answers1

2

Covert your spring:hidden tag to normal html hidden tag:

<form:hidden path="items[${status.index}].id"/>

to

<input type="hidden" name="id" value="${item.id}"/>
Viral Patel
  • 8,506
  • 3
  • 32
  • 29
  • Have replaced it to what you said but still ain't getting the item through the post method. The item is still with no content. – Skyverian Dec 17 '12 at 14:38
  • It does fill in the item id in the Item now but it's not getting all the item data out. Or I am just misunderstanding the attribute of @ModelAttribute :(. – Skyverian Dec 17 '12 at 15:15
  • Sorry I completely lost you!! – Viral Patel Dec 17 '12 at 15:16
  • The thing I wanted is that if I press on the submit button that it is going pass the whole item with all the data that the item has. But with the input type hidden you gave it only pass the id from the item but not all the data from the item. – Skyverian Dec 17 '12 at 15:19
  • oh my bad i have misunderstood the functional thing but :) haha your answer is right. So many thanks ^^ for your answer =D. I just need to use an converter to parse the data into it after the post. thanks thanks :) – Skyverian Dec 17 '12 at 15:25