Reputation: 51
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.
Upvotes: 2
Views: 4241
Reputation: 51
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
Upvotes: 3
Reputation: 244
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());
}
Upvotes: 1