简体   繁体   English

将对象从下拉列表(.jsp)传递到控制器

[英]Pass object from Dropdown list (.jsp) to Controller

I'm trying to pass an object (or just the ID) to my controller, which I select from a dropdown list. 我试图将一个对象(或只是ID)传递给我的控制器,该控制器是我从下拉列表中选择的。 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: 有2个类: productcategoryproduct包含一个外键,这是category的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;
}

As you can see, I'm passing the object category into my .jsp. 如您所见,我正在将对象类别传递到我的.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: 尝试这样的事情:

@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 即使是为了更好地说明和简化,也请尝试使用spring表单标签,该标签提供了更多的设施来处理这种情况

Add an Id to your select - the id is added as a request parameter. 将一个ID添加到您的选择中-该ID作为请求参数添加。

<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 如果您的产品产品具有categoryId字段(带有setter),则可以仅使用产品产品,而不能使用长的categoryId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM