how to call spring controller @RequestMapping from another action method passing form object along with the call

12,914

You can use RedirectAttributes.

In below example, when foo is invoked and redirects to /bar, the model will contain xyz=meow attribute.

@RequestMapping(..)
public String foo(RedirectAttributes redir) {
  redir.addFlashAttribute("xyz", "meow");
  return "redirect:/bar";
}

@RequestMapping("/bar")
public String bar(Model model) {
  ..
}

If you find doing this too many time you might also consider using @SessionAttributes

Share:
12,914

Related videos on Youtube

romil gaurav
Author by

romil gaurav

Software Engineer

Updated on June 04, 2022

Comments

  • romil gaurav
    romil gaurav almost 2 years

    I need to call another @RequestMapping from inside of a spring controller. Now I can easily do it by

        return "redirect:anotherMapping.htm";
    

    But the I need to pass value in form object as well.

        @RequestMapping("/anotherMapping")
        public ModelAndView addUser(final @ModelAttribute("userLogin") UserLogin 
        userLogin, final HttpServletRequest request){
    

    I need to pass userId in UserLogin. If I write return "redirect:anotherMapping.htm";, then it invokes this controller method but form object is null.

    Please help.

    • Sotirios Delimanolis
      Sotirios Delimanolis about 10 years
      Look into RedirectAttributes.
    • Rey Libutan
      Rey Libutan about 10 years
      Is it within the same controller?
    • romil gaurav
      romil gaurav about 10 years
      I think there is no way to pass the form object too in the controller, is it?
  • romil gaurav
    romil gaurav about 10 years
    'i think this will definately help. I know I could use session or static variable to set the id and then set it explicitly in the form object, but those were not the best methodology. Also I think there is no way to pass the form object too in the controller, is it? Thanks bro for the help.
  • gerrytan
    gerrytan about 10 years
    What do you mean "there is no way to pass the form object too in the controller"? You can use @ModelAttribute and @SessionAttribute