SpingMVC实现集合参数(Could not instantiate bean class [java.util.List])

需求,要求批量新增或者修改一个List,在springMVC中是不支持下面代码的写法:

复制代码
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(List<ProductCollocation> productCollocations ,HttpServletRequest request, RedirectAttributes redirectAttributes) {
  for (ProductCollocation productCollocation : productCollocations) {
    productCollocation.setModifyDate(DateUtil.getDate());
    productCollocationService.update(productCollocation, "create_date","product","collocation","description");
  }
  addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
  return "redirect:list.jhtml";
}
复制代码

这样写会抛出如下异常:

nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.List]: 

是否其实也很简单,Spring MVC 需要支持Form表单对象的方式映射,使用get set器来填充对象。

新增一个Form

复制代码
public class ProductCollocationForm {
    List<ProductCollocation> productCollocations;

    /**
     * @return the productCollocations
     */
    public List<ProductCollocation> getProductCollocations() {
        return productCollocations;
    }

    /**
     * @param productCollocations the productCollocations to set
     */
    public void setProductCollocations(List<ProductCollocation> productCollocations) {
        this.productCollocations = productCollocations;
    }
}
复制代码

再使用Form来set对象

复制代码
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(ProductCollocationForm productCollocationForm ,HttpServletRequest request, RedirectAttributes redirectAttributes) {
    for (ProductCollocation productCollocation : productCollocationForm.getProductCollocations()) {
      productCollocation.setModifyDate(DateUtil.getDate());
      productCollocationService.update(productCollocation, "create_date","product","collocation","description");
    }
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:list.jhtml";
}
复制代码

前台就能够使用索引的方式对后台对象设置值了

<td>
  <input type="text" name="productCollocations[${productCollocation_index}].displayName" class="text" maxlength="200"  style="width:100px"  value="${productCollocation.displayName}"/>
  <input type="hidden" name="productCollocations[${productCollocation_index}].id" class="text" maxlength="200" value="${productCollocation.id}"/>
</td>

上面页面中name的值为:productCollocations[${productCollocation_index}].displayName,其实也相当于productCollocations[0].displayName、productCollocations[1].displayName类似这种的写法

posted @   岁月淡忘了谁  阅读(2050)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示