Pergunta

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.

Foi útil?

Solução

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}"/>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top