美文网首页
springMVC杂记

springMVC杂记

作者: 静心安分读书 | 来源:发表于2018-07-22 09:34 被阅读9次

    18.7.30
    springmvc给controller传参数,传递数组。不可以用List接收,但是可以使用java8新特性的Iterable<>。如果需要List,还是需要遍历一遍。
    List<InquiryProductOffer> inquiryProductOffers = new LinkedList<>();
    productOfferVOs.forEach(item -> {
    InquiryProductOffer inquiryProductOffer = InquiryProductOffer.builder()
    .inquiryId(Long.parseLong(item.getInquiryId()))
    .winNumber(item.getWinNumber())
    .winTotalPrice(item.getWinTotalPrice())
    .build();
    inquiryProductOffers.add(inquiryProductOffer);
    });
    ——————————
    18.7.22
    1、实际项目中遇到一个问题:
    前台向后台传递了一个数组。后台controller的参数是List<自定义类>
    数据无法接收且报错:Failed to instantiate [java.util.List]: Specified class is an interface;

    查询错误问题,发现是前端传递的对象,后台没有set,get的实体接收。
    controller中参数List内封装的不是基本数据类型,而是一个对象,springMVC源码获取前台的参数是:request.getParameter("")来接收参数的,这样的话,封装参数时就出问题了。

    解决办法:将List<>封装成对象,提供set、get方法,作为参数。

    参考:https://blog.csdn.net/Alice_qixin/article/details/71403043
    ——————————
    2、springmvc中的数据绑定(前后台传递)
    2.1、基本类型数据绑定:前台必须传递正确的变量名,否则会返回500。
    2.2、包装类型参数绑定:不必须带变量名,返回null。
    2.3、数组元素绑定:直接用,user?name=xiaoshu&name=xiaozhang
    2.4、多层级对象的绑定: 在user类中加入一个admin的对象属性
    public User getUser(User user)
    http://localhost:8080/user?name=xiaoshu&id=1&address=hangzhou&admin.name=xiaoli
    2.5、同属性对象参数绑定
    这里有两个对象user和admin,它们有两个相同的属性name和address
    public String list(User user, Admin admin)
    http://localhost:8080/list?name=xiaoshu&address=home
    得到:User{id=null, name='xiaoshu', address='home'}Admin{name='xiaoshu', address='home'}
    我们可以通过在controller中配置一个@InitBinder进行分开绑定

    @InitBinder("user")
    public void initUser(WebDataBinder binder){
    binder.setFieldDefaultPrefix("user.");
    }
    @InitBinder("admin")
    public void initAdmin(WebDataBinder binder){
    binder.setFieldMarkerPrefix("admin.");
    }
    http://localhost:8080/list?user.name=xiaoshu&user.address=home
    结论:进行同属性参数绑定时,要区分绑定时需在属性前加上对象前缀,并在controller中配置@InitBinder来明确哪个前缀的属性绑定到哪个对象中
    没有配置@InitBinder加前缀不能成功绑定
    2.6、List绑定
    结论:这里不能直接用List去绑定,而是要创建一个类类中创建一个List去绑定,AdminList中创建了一个ArrayList。
    2.7Map绑定
    public AdminMap getMap(AdminMap adminMap)
    http://localhost:8080/map?admins['X'].name=xiaoshu&admins['Y'].name=xiaozhang
    结论:map存放可以保证key的唯一性,过滤冲重复数据
    2.8、表单多对象传递的绑定(特别是多对象的属性名相同的情况)
    也就是2.5所讲。

    参考:https://blog.csdn.net/happyaliceyu/article/details/79240717

    相关文章

      网友评论

          本文标题:springMVC杂记

          本文链接:https://www.haomeiwen.com/subject/chklmftx.html