I'm trying to pass an object (or just the ID) to my controller, which I select from a dropdown list. There are 2 classes: product and category (product contains a foreign key, which is the ID of category) This is how I load it into:
@RequestMapping(value="/edit", method=RequestMethod.GET)
public ModelAndView edit(@RequestParam(required=false) Long id) {
ModelAndView mv = new ModelAndView();
if (id == null) {
mv.addObject(new Product());
} else {
mv.addObject("product", productDao.findById(id));
}
mv.addObject("category", categoryDao.findAll());
mv.setViewName("edit-product");
return mv;
}
As you can see, I'm passing the object category into my .jsp. There I'm displaying all the categories the user can select.
<select name="category">
<c:forEach items="${category}" var="category">
<option name="category" value="${category.id}">${category.name}</option>
</c:forEach>
</select>
The value should be passed to my controller, but I don't know how to pass it.
@RequestMapping(value="/save", method=RequestMethod.POST)
public String save(Product product, Category category, Model model) {
product.setCategory(category); //not working, since the parameter isn't correct
Product result = productDao.save(product);
// set id from create
if (product.getId() == null) {
product.setId(result.getId());
}
Try something like this:
Even for better clarity and simplification try to use spring form tags, that provide even more facilities to handle these kind of scenario
Add an Id to your select - the id is added as a request parameter.
And the controller to get the value
If your Product product has categoryId field (with setter) you can use just Product product rather than Long categoryId