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

后端 未结 10 1291
暗喜
暗喜 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;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 13:59

    Using just redirectAttributes.addFlashAttribute(...) -> "redirect:..." worked as well, didn't have to "reinsert" the model attribute.

    Thanks, aborskiy!

    0 讨论(0)
  • 2020-11-27 14:02

    I had same problem.

    With RedirectAttributes after refreshing page, my model attributes from first controller have been lost. I was thinking that is a bug, but then i found solution. In first controller I add attributes in ModelMap and do this instead of "redirect":

    return "forward:/nameOfView";

    This will redirect to your another controller and also keep model attributes from first one.

    I hope this is what are you looking for. Sorry for my English

    0 讨论(0)
  • 2020-11-27 14:09

    Maybe you could do it like this:

    Don't use the model in first controller. Store data in some other shared object which could be then retrieved by second controller.

    Look at this and this post. It's about the similar issue.

    P.S.

    You could probabbly use session scoped bean for that shared data...

    0 讨论(0)
提交回复
热议问题