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

【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]: 

是否事实上也非常easy,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>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/118343.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号