ajm
ajm

Reputation: 13203

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.

Upvotes: 44

Views: 117453

Answers (10)

john kothapeta
john kothapeta

Reputation: 1

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

[ Input to the first Controller][1]

[]: https://i.sstatic.net/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;
    }
}

Upvotes: -1

JPRLCol
JPRLCol

Reputation: 200

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

Upvotes: 0

Mayur Shah
Mayur Shah

Reputation: 41

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

Upvotes: 4

Michal Ambrož
Michal Ambrož

Reputation: 167

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

Upvotes: 1

DinkoCejvanovic
DinkoCejvanovic

Reputation: 31

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

Upvotes: 3

aborskiy
aborskiy

Reputation: 1347

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

Upvotes: 117

pkopac
pkopac

Reputation: 1035

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

Thanks, aborskiy!

Upvotes: 15

danny.lesnik
danny.lesnik

Reputation: 18639

I think that the most elegant way to do it is to implement custom Flash Scope in Spring MVC.

the main idea for the flash scope is to store data from one controller till next redirect in second controller

Please refer to my answer on the custom scope question:

Spring MVC custom scope bean

The only thing that is missing in this code is the following xml configuration:

<bean id="flashScopeInterceptor" class="com.vanilla.springMVC.scope.FlashScopeInterceptor" />
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
  <property name="interceptors">
    <list><ref bean="flashScopeInterceptor"/></list>
  </property>
</bean>

Upvotes: 14

Matjaz Muhic
Matjaz Muhic

Reputation: 5588

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

Upvotes: 0

Pokuri
Pokuri

Reputation: 3082

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

Upvotes: -2

Related Questions