List as form backing object using Spring 3 MVC, correct syntax?

后端 未结 2 1780
不知归路
不知归路 2020-11-28 07:09

I want to do something like this, where Foo is a class with one String field name, and getter/setter:



        
2条回答
  •  醉话见心
    2020-11-28 07:43

    Maybe this answersyour question:

    CONTROLLER :

    @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 fooList;
    
        public FooListWrapper() {
             this.fooList = new ArrayList();
        }
    
        public List getFooList() {
            return fooList;
        }
    
        public void setFooList(List fooList) {
            this.fooList = fooList;
        }
    
        public void add(Foo foo) {
            this.fooList.add(foo);
        }
    }
    

    FOO CLASS :

    public class Foo {
        private String name;
    
        public Foo() {
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    JSP VIEW (name = fooForm):

    
    
    
    
        
               
        
    
    
        
    
    

提交回复
热议问题