Spring MVC / JSP处理庞大的表单

时间:2013-08-21 18:18:09

标签: forms spring jsp spring-mvc

我在前端显示了一个类的几个实例,用户可以在其中更改对象的每个属性,这可以在单个表单中添加多达1000 <select>个。

@Entity
public class Entity extends ModelBase{
    @OneToOne
    private AnotherEntity entityInstance;
    @Enumerated(EnumType.STRING)
    private AEnum sessionOne = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionTwo = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionThree = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionFour = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionFive = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionSix = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionSeven = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionEight = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionNine = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionTen = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionEleven = AEnum.None;
    @Enumerated(EnumType.STRING)
    private AEnum sessionTwelve = AEnum.None;

        ...
}

JSP文件

<form>
  <table>
    <tr>
      <td><select for sessionOne></td>
      <td><select for sessionTwo></td>
      <td><select for sessionThree></td>
      <td><select for sessionFour></td>
      <td><select for sessionFive></td>
      <td><select for sessionSix></td>
      <td><select for sessionSeven></td>
      <td><select for sessionEight></td>
      <td><select for sessionNine></td>
      <td><select for sessionTen></td>
      <td><select for sessionEleven></td>
      <td><select for sessionTwelve></td>
    </tr>
    ...
  </table>
  <button type="submit">
</form>

提交表单的最佳方式是什么?运行投掷每个选择名称似乎不是最好的方式。

1 个答案:

答案 0 :(得分:0)

尝试使用spring“form”taglib。您可以创建封装所有字段的特殊类,并将其传递给“GET”方法(显示页面)中的模型。假设传递的对象的名称是“entity”。您还必须将所有枚举值的列表传递给模型。 (参见此处的示例:spring-form:options tag with enum)。 Jsp将如下所示:

<form:form commandName="entity" action="/action" method="POST">
    <form:select path="sessionOne">
        <form:options items="${availableOptions}" />
    </form:select>
    <form:select path="sessionTwo">
        <form:options items="${availableOptions}" />
    </form:select>
    <!-- and so on -->
</form:>

控制器代码:

@RequestMapping(value = "/action", method = RequestMethod.POST)
public String handleHugeForm(@ModelAttribute Entity entity) {
    // do what you want
}

Spring“form”taglib教程:http://www.dzone.com/tutorials/java/spring/spring-form-tags-1.html