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

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

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




  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值