【问题标题】:Map Struts2 form to a Bean with Collection field将 Struts2 表单映射到带有 Collection 字段的 Bean
【发布时间】:2015-11-24 09:59:07
【问题描述】:

我有这样定义的 Person & Fruit bean:

public class Person {
    private String fullName;
    private List<Fruit> favoriteFruits;
    //getters setters and constructors here.
    ...
}

public class Fruit {
    private String name;
    //getter setter and constructors here.
}

然后我有一个这样的 Struts2 Action:

public class AddPersonAction extends ActionSupport {
    private static final long serialVersionUID = -1856680463263215989L;

    private Person person;

    @Override
    public String execute() throws Exception {      
        if (person!= null) {            
            //TODO add person to database.          
            return SUCCESS;
        } else {            
            return INPUT;
        }
    }    
}

Strus2 html 表单如下所示:

...
<form...>
  <s:textfield name="person.fullName"/>

  <!--This is where I would allow user to create one or more textboxes using javascript. 
    And allow them to input multiple favorite fruits -->

  <s:submit name="submit" value="Submit" />
</form>
...

现在,我的问题是,我将名为 person.fullName 的文本字段直接映射到 Person bean 的 fullName 属性的方式,如何将多个文本框(最喜欢的水果)映射到 Person bean 的 favoriteFruits 集合(@987654327 @) ?

【问题讨论】:

    标签: jsp collections struts2


    【解决方案1】:

    要发回一个集合而不是单个值,use an index

    <s:textfield value="person.favoriteFruits[0].name" />
    <s:textfield value="person.favoriteFruits[1].name" />
    ...
    

    要使用 Javascript 创建它,请关注 this question and answer 并简单地计算一下。

    还要记得always specify a no-args constructor(如果自己创建构造函数,否则没有必要,因为它默认存在)以允许Struts2正确映射

    【讨论】:

      猜你喜欢
      • 2012-10-02
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      相关资源
      最近更新 更多