前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【FAQ】SpingMVC实现集合參数(Could not instantiate bean class [java.util.List])

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

作者头像
全栈程序员站长
发布2022-07-13 16:06:48
1760
发布2022-07-13 16:06:48
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

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

代码语言:javascript
复制
	@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";
	}

会抛出异常

代码语言:javascript
复制
nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.List]: 

是否事实上也非常easy,Spring MVC 须要支持Form表单对象的方式映射,使用get set器来填充对象。

新增一个Form

代码语言:javascript
复制
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对象

代码语言:javascript
复制
	@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";
	}

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

代码语言:javascript
复制
<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.cn/118343.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年12月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档