使用spring 3 mvc列出<Foo>作为表单后备对象,语法是否正确?

Nim*_*sky 20 spring jsp jstl spring-mvc

我想做这样的事情,其中​​foo是一个带有一个String字段名的类,以及getter/setter:

<form:form id="frmFoo" modelAttribute="foos">
   <c:forEach items="${foos}" var="foo">
     <form:input path="${foo.name}" type="text"/>
Run Code Online (Sandbox Code Playgroud)

然后提交更新名称的Foos完整列表?我的控制器sig看起来像这样:

@RequestMapping(value = "/FOO", method = RequestMethod.POST)
public String getSendEmail(List<Foo> foos, Model model) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

Fat*_*ton 33

也许这回答你的问题:

控制器:

@Controller("/")
public class FooController{

    //returns the ModelAttribute fooListWrapper with the view fooForm
    @RequestMapping(value = "/FOO", method = RequestMethod.GET)
    public String getFooForm(Model model) {
        FooListWrapper fooListWrapper = new FooListWrapper();
        fooListWrapper.add(new Foo());
        fooListWrapper.add(new Foo());

        //add as many FOO you need

        model.addAttribute("fooListWrapper", fooListWrapper);

        return "fooForm";
    }

    @RequestMapping(value = "/FOO", method = RequestMethod.POST)
    public String postFooList(@ModelAttribute("fooListWrapper")FooListWrapper fooListWrapper, Model model) {

        //...........
    }

}
Run Code Online (Sandbox Code Playgroud)

FOO LIST WRAPPER:

public class FooListWrapper {
    private List<Foo> fooList;

    public FooListWrapper() {
         this.fooList = new ArrayList<Foo>();
    }

    public List<Foo> getFooList() {
        return fooList;
    }

    public void setFooList(List<Foo> fooList) {
        this.fooList = fooList;
    }

    public void add(Foo foo) {
        this.fooList.add(foo);
    }
}
Run Code Online (Sandbox Code Playgroud)

FOO CLASS:

public class Foo {
    private String name;

    public Foo() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

JSP VIEW(name = fooForm):

<c:url var="fooUrl" value="/FOO"/>
<form:form id="frmFoo" action="${fooUrl}" method="POST" modelAttribute="fooListWrapper">


    <c:forEach items="${fooListWrapper.fooList}" varStatus="i">
           <form:input path="fooList[${i.index}].name" type="text"/>
    </c:forEach>


    <button>submit</button>
</form:form>
Run Code Online (Sandbox Code Playgroud)

  • 我假设这个解决方案需要一个固定数量的输入字段,这是正确的吗?如果您有动态数量的输入字段怎么办?例如,我需要让我的用户动态生成新的输入字段.你知道如何处理这种情况吗? (8认同)
  • Spring 4有新的解决方案吗?因为在这个例子中需要编写"listwrapper",这是非常无聊的^^ (5认同)
  • 你会如何在Thymeleaf做到这一点? (2认同)