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

后端 未结 2 1774
不知归路
不知归路 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:41

    Although the above answer works, here's an alternate that does not require you to create a wrapper class/ form class.

    Model And Controller

    public class Foo {
        private String name;
        private List fooList; //**must create this list, also getter and setter**
        public Foo() {
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
        public List getFooList() {
            return fooList;
        }
    
        public void setFooList(String fooList) {
            this.fooList = fooList;
        }
    
    }
    
    @Controller("/")
    public class FooController{
    
        //returns the ModelAttribute fooListWrapper with the view fooForm
        @RequestMapping(value = "/FOO", method = RequestMethod.GET)
        public String getFooList(Model model) {
            List fooList = service.getFooList();
    
            model.addAttribute("fooList", fooList);
    
            return "list_foo"; //name of the view
        }
    
        @RequestMapping(value = "/FOO", method = RequestMethod.POST)
        public String postFooList(@ModelAttribute("foo")Foo foo, Model model) {
            List list = foo.getFooList(); // **This is your desired object. 
            //If you debug this code, you can easily find this is the list of  
            //all the foo objects that you wanted, provided you pass them properly. 
            //Check the jsp file to see one of the ways of passing such a list of objects**
            //Rest of the code
        }
    
    }
    

    JSP View

    
    
    
        
               
               
        
    
    
        
    
    

提交回复
热议问题