How to pass model attributes from one Spring MVC controller to another controller?

后端 未结 10 1333
暗喜
暗喜 2020-11-27 13:19

I am redirecting from a controller to another controller. But I also need to pass model attributes to the second controller.

I don\'t want to put the model in sessi

10条回答
  •  余生分开走
    2020-11-27 13:58

    By using @ModelAttribute we can pass the model from one controller to another controller

    [ Input to the first Controller][1]

    []: https://i.stack.imgur.com/rZQe5.jpg from jsp page first controller binds the form data with the @ModelAttribute to the User Bean

    @Controller
    public class FirstController {
        @RequestMapping("/fowardModel")
        public ModelAndView forwardModel(@ModelAttribute("user") User u) {
            ModelAndView m = new ModelAndView("forward:/catchUser");
            m.addObject("usr", u);
            return m;
        }
    }
    
    @Controller
    public class SecondController {
        @RequestMapping("/catchUser")
        public ModelAndView catchModel(@ModelAttribute("user")  User u) {
            System.out.println(u); //retrive the data passed by the first contoller
            ModelAndView mv = new ModelAndView("userDetails");
            return mv;
        }
    }
    

提交回复
热议问题