小编典典

清单 使用Spring 3 MVC作为表单支持对象,正确的语法?

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"/>

然后提交名称完整的Foos完整列表?

我的控制器如下所示:

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

阅读 361

收藏
2020-06-01

共1个答案

小编典典

也许这回答了您的问题:

控制器:

@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) {

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

}

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);
    }
}

FOO类:

public class Foo {
    private String name;

    public Foo() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

JSP VIEW(名称= 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>
2020-06-01