Akhil
Akhil

Reputation: 83

redirect with model object in spring

i need to pass an object into a page that i'm going to redirect

@RequestMapping(value = "/createNewQuest",method={ RequestMethod.GET, RequestMethod.POST })
    public ModelAndView createNewQuest(Quest quest,ModelAndView mav) {
        questService.addQuest(quest);


        mav.addObject("quest", quest);
        mav.setViewName("redirect:/control/displayQuest");
        return mav;
    }

my controller class seems like this but displayQuest page not getting the quest object?

any help wil be greatly appreciabl..

Upvotes: 4

Views: 7797

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

Spring added Flash Attributes to handle this scenario:

Annotated controllers typically do not need to work with FlashMap directly. Instead an @RequestMapping method can accept an argument of type RedirectAttributes and use it to add flash attributes for a redirect scenario. Flash attributes added via RedirectAttributes are automatically propagated to the "output" FlashMap. Similarly after the redirect attributes from the "input" FlashMap are automatically added to the Model of the controller serving the target URL.

Example

    @RequestMapping(value = "/createNewQuest",method={ RequestMethod.GET, RequestMethod.POST })
    public ModelAndView createNewQuest(@ModelAttribute("quest") Quest quest,
         BindingResult binding, ModelAndView mav, 
             final RedirectAttributes redirectAttributes) {

        questService.addQuest(quest);

        redirectAttributes.addFlashAttribute("quest", quest);
        mav.setViewName("redirect:/control/displayQuest");
        return mav;
    }

Upvotes: 4

pappu_kutty
pappu_kutty

Reputation: 2488

if you are using spring form tag , then your form tag should look like below

<form:form name="yourformname" id="formid" commandName="quest">

then you controller model object "quest" will be mapped to spring form tag commandName variable, later you can access the variable

Upvotes: 0

Related Questions