Spring MVC not populating model attribute

I am trying to populate the object using model attribute. It's returning null from JSP to controller.

<form:form method="post" action="addProduct" modelAttribute="product">
    <table>
        <tr>
            <td>Product Name :</td>
            <td><form:input path="productName"/></td>
        </tr>
        <tr>
            <td>Parent Product Id:</td>
            <td><form:input path="parentId"/></td>
        </tr>
        <tr>
            <td>Category Id:</td>
            <td><form:input path="categoryId"/></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="AddProduct"></td>
        </tr>
    </table>
</form:form>

@Autowired
private ProductService productService;

@RequestMapping(value = "addProduct", method = RequestMethod.GET)
public ModelAndView productForm(@ModelAttribute("product") Product product){
    return new ModelAndView("addProduct"));
}

@RequestMapping(value = "addProduct", method = RequestMethod.POST)
public ModelAndView insertProduct(@ModelAttribute("product") Product product){
    System.out.println(product.getProductName() + " : " + product.getParentId() + " : " + product.getCategoryId());
    productService.insert(product);
    return new ModelAndView("success");
}

While getting the values back in controller using modelAttribute it's coming as null. What am I doing wrong?

Also there is one more thing I am doing same thing in my Catergory class, which is working perfectly fine.

Not able to understand what's wrong in here.

Answers


It doesn't look like you are actually adding a model to your ModelAndView.

This would pass a new Product object to your form:

@RequestMapping(value = "addProduct", method = RequestMethod.GET)
public ModelAndView productForm(){
    return new ModelAndView("addProduct", "product", new Product());
}

Finally I found the solution to my problem.

In my pojo class I had given different Name for the setter due to which it was unable to run.

Ex: In my JSP i was giving

<form:input path="productName"/>

Where my path name is "productName" and in my POJO class i gave the same name for the variable but my setter name was different.

So in order to set the attribute value Spring will look for the setter with name of set + attributeName().

Where in this above case it will be set + productName()

And my mistake was my setter had the name setName().

Hope this helps the newbies of Spring like me. Thanks


Need Your Help

Adding another layer to the scene in the HelloWorld project

cocos2d-iphone cocos2d-x

In the cocos2d-x HelloWorld project, I am trying to add another layer to the scene and keep a reference to this layer in a data member. Since the function HelloWorld::scene() is static, I cannot ad...

Linq query to pick up field if it is null or matches specific value

.net linq

I'm trying to write a Linq query that checks three fields: StateCode, ChannelCode, and ZipCode.