Pass object from Dropdown list (.jsp) to Controlle

2019-09-14 15:37发布

问题:

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());
}

回答1:

Add an Id to your select - the id is added as a request parameter.

<select name="category" id="categoryId">

And the controller to get the value

public String save(@RequestParam("categoryId") Long categoryId, Model model)

If your Product product has categoryId field (with setter) you can use just Product product rather than Long categoryId



回答2:

Try something like this:

@RequestMapping(value="/save", method=RequestMethod.POST)
public String save(@ModelAttribute Product product,@ModelAttribute Category 
category, Model model) {  
// Your code here, 
//at this point you have full access to Product and Category object 
//One more thing your input tag's name attribute must have same name as of 
//your POJO's fields name 
}

Even for better clarity and simplification try to use spring form tags, that provide even more facilities to handle these kind of scenario