Search code examples
springspring-mvcpost-redirect-get

Spring pass model from POST


I'm quite knowledgeable with Spring yet. I'm trying to learn. Please help me quite a bit.

I have a form which uses modelAttribute="projectBean" which is working perfectly fine and I'm able to manipulate data on the controller below

@RequestMapping( value = "projects/newProject", method = RequestMethod.POST )
public String newProject( @ModelAttribute( "projectBean" )
ProjectBean projectBean, HttpServletRequest request, ModelMap model )
{

    model.addAttribute( "projectBean", projectBean );

    return "redirect:../projects/projectItems.do";
}

I'm done saving it to the database so I want now to pass the projectBean to another controller

@RequestMapping( value = "/projects/projectItems", method = RequestMethod.GET )
public String projectItems( @RequestParam( defaultValue = "" )
String message, @RequestParam( defaultValue = "" )
String messageType, @RequestParam( defaultValue = "" )
String projectID, HttpServletRequest request, @RequestParam( "projectBean" )
ProjectBean projectBean, ModelMap model )
{

    return "project/items";
}

But i'm having this exception: Required ProjectBean parameter 'projectBean' is not present

What am I doing wrong?


Solution

  • You don't generally pass a model from one Controller to another Controller. I assume you are trying to perform some logic before passing the model to another JSP page (project/items in this case).

    You can achieve the same in newProject() controller rather than trying to pass the model to another Controller

    @RequestMapping( value = "projects/newProject", method = RequestMethod.POST )
    public String newProject( @ModelAttribute( "projectBean" )
    ProjectBean projectBean, HttpServletRequest request, RedirectAttributes redirectAttributes)
    {
    
        //Call DAO class to save the model to database
    
        //Call BusinessDelegate class to perform the additional logic
    
        //Add beans to RedirectAttributes using addFlashAttribute() methods to make it available in next JSP page
        redirectAttributes.addFlashAttribute("projectBean", projectBean);
    
        return "redirect:/project/items";
    }
    

    Note: In order to apply POST-REDIRECT-GET pattern, you should use RedirectAttributes instead of ModelMap to make the model attributes available in redirected JSP page.