将对象从下拉列表(.jsp)传递到控制器 [英] Pass object from Dropdown list (.jsp) to Controller
问题描述
我试图将一个对象(或只是ID)传递给我的控制器,该控制器是我从下拉列表中选择的.有2个类别: product 和 category ( product 包含一个外键,这是 category 的ID)这就是我将其加载到的方式:
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;
}
如您所见,我正在将对象 category 传递到我的.jsp文件中.我正在显示用户可以选择的所有类别.
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());
}
推荐答案
将ID添加到您的选择中-该ID作为请求参数添加.
Add an Id to your select - the id is added as a request parameter.
<select name="category" id="categoryId">
和获取值的控制器
public String save(@RequestParam("categoryId") Long categoryId, Model model)
如果您的产品"产品具有"categoryId"字段(带有setter),则可以仅使用产品"产品,而不能使用长" categoryId
If your Product product has categoryId field (with setter) you can use just Product product rather than Long categoryId
这篇关于将对象从下拉列表(.jsp)传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!