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

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 session.

Please help.

This question is related to redirect spring-mvc controllers modelattribute

The answer is


You can resolve it by using org.springframework.web.servlet.mvc.support.RedirectAttributes.

Here is my controller sample.

@RequestMapping(method = RequestMethod.POST)
    public String eligibilityPost(
            @ModelAttribute("form") @Valid EligibiltyForm form,
            Model model,
            RedirectAttributes redirectAttributes) {
        if(eligibilityService.validateEligibility(form)){
            redirectAttributes.addFlashAttribute("form", form);
            return "redirect:<redirect to your page>";
        }
       return "eligibility";
    }

read more on my blog at http://mayurshah.in/596/how-do-i-redirect-to-page-keeping-model-value


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";  
}

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;
    }
}

If you want just pass all attributes to redirect...

public String yourMethod( ...., HttpServletRequest request, RedirectAttributes redirectAttributes) {
    if(shouldIRedirect()) {
        redirectAttributes.addAllAttributes(request.getParameterMap());
        return "redirect:/newPage.html";
    }
}

Add all model attributes to the redirecting URL as query string.


I used @ControllerAdvice , please check is available in Spring 3.X; I am using it in Spring 4.0.

@ControllerAdvice 
public class CommonController extends ControllerBase{
@Autowired
MyService myServiceInstance;

    @ModelAttribute("userList")
    public List<User> getUsersList()
    {
       //some code
       return ...
    }
}

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


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

Thanks, aborskiy!


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...


Examples related to redirect

React-Router External link Laravel 5.4 redirection to custom url after login How to redirect to another page in node.js How to redirect to an external URL in Angular2? How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template? Use .htaccess to redirect HTTP to HTTPs How to redirect back to form with input - Laravel 5 Using $window or $location to Redirect in AngularJS yii2 redirect in controller action does not work? Python Requests library redirect new url

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Examples related to controllers

How to pass model attributes from one Spring MVC controller to another controller? Display a view from another controller in ASP.NET MVC

Examples related to modelattribute

How to pass model attributes from one Spring MVC controller to another controller? What is @ModelAttribute in Spring MVC?