将对象从下拉列表(.jsp)传递给Controller

时间:2017-04-18 12:01:30

标签: java spring jsp spring-mvc model-view-controller

我正在尝试将一个对象(或只是ID)传递给我的控制器,我从下拉列表中选择它。共有2个类:产品类别产品包含外键,即类别的ID)这就是我加载它的方式:

@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;
}

如您所见,我将对象 category 传递给我的.jsp。我在那里显示用户可以选择的所有类别。

<select name="category">
<c:forEach items="${category}" var="category">
    <option name="category" value="${category.id}">${category.name}</option>
</c:forEach>
</select> 

该值应传递给我的控制器,但我不知道如何传递它。

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

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

@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 
}

即使为了更好的清晰度和简化,尝试使用弹簧形式标签,它提供了更多的设施来处理这种情况

答案 1 :(得分:1)

在您的选择中添加ID - 将ID添加为请求参数。

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

控制器获取值

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

如果您的产品产品有categoryId字段(使用setter),您只能使用产品而非Long categoryId