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

编程入门 行业动态 更新时间:2024-10-25 05:27:36
本文介绍了将对象从下拉列表(.jsp)传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图将一个对象(或只是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)传递到控制器

本文发布于:2023-10-07 17:29:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1470030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   对象   列表   jsp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!