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

后端 未结 10 1330
暗喜
暗喜 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:47

    I use spring 3.2.3 and here is how I solved similar problem.
    1) Added RedirectAttributes redirectAttributes to the method parameter list in controller 1.

    public String controlMapping1(
            @ModelAttribute("mapping1Form") final Object mapping1FormObject,
            final BindingResult mapping1BindingResult,
            final Model model, 
            final RedirectAttributes redirectAttributes)
    

    2) Inside the method added code to add flash attribute to redirectAttributes redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);

    3) Then, in the second contoller use method parameter annotated with @ModelAttribute to access redirect Attributes

    @ModelAttribute("mapping1Form") final Object mapping1FormObject
    

    Here is the sample code from Controller 1:

    @RequestMapping(value = { "/mapping1" }, method = RequestMethod.POST)
    public String controlMapping1(
            @ModelAttribute("mapping1Form") final Object mapping1FormObject,
            final BindingResult mapping1BindingResult,
            final Model model, 
            final RedirectAttributes redirectAttributes) {
    
        redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);
    
        return "redirect:mapping2";
    }   
    

    From Contoller 2:

    @RequestMapping(value = "/mapping2", method = RequestMethod.GET)
    public String controlMapping2(
            @ModelAttribute("mapping1Form") final Object mapping1FormObject,
            final BindingResult mapping1BindingResult,
            final Model model) {
    
        model.addAttribute("transformationForm", mapping1FormObject);
    
        return "new/view";  
    }
    

提交回复
热议问题