zoukankan      html  css  js  c++  java
  • 【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="100px"  value="${productCollocation.displayName}"/>
    				   <input type="hidden" name="productCollocations[${productCollocation_index}].id" class="text" maxlength="200" value="${productCollocation.id}"/>
    				</td>




  • 相关阅读:
    洛谷 P1045 【麦森数】快速幂
    洛谷 P4838 P哥破解密码 题解
    洛谷 P1609 最小回文数 题解
    洛谷 P4910 帕秋莉的手环 矩阵乘法+快速幂详解
    [SDOI2010]外星千足虫 题解 高斯消元+bitset简介
    UVA1386 【Cellular Automaton】题解
    JavaScript基础(.....持续待更)
    网页布局基础
    css浮动--float/clear通俗讲解(转载)
    css基础
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4013190.html
Copyright © 2011-2022 走看看