Todd
Todd

Reputation: 153

Spring MVC 3.1 - RedirectAttributes not part of model after redirect

I'm looking to develop a Spring MVC application that incorporates the POST/Redirect/GET pattern and input validation. In the POST phase, I execute a Validator and get back a BindingResult/Errors collection. If there are errors, I'd like to redirect back to the form with my validation errors in tact. I want this to be a redirect that resolves as a GET request as to avoid expired caches and form resubmission prompts when using the browser's navigation buttons (back, forward, refresh).

This is how I'm handling the initial form display and is where I want to redirect the user back to if there are validation errors.

@RequestMapping("/account/list")
public String listAccounts(HttpServletRequest request, Map<String, Object> map) {

    log.debug("start of list accounts");

    map.put("accountList", entityService.listAccounts());
    map.put("account", new Account());
    map.put("accountTypeValues", AccountTypes.values());

//      Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
//      if (inputFlashMap != null) {
//          map.putAll(inputFlashMap);
//      }

    return "account";
}

This is a snippet of the method that processes the POST:

@RequestMapping(value = "/account/add", method = RequestMethod.POST)
public String addAccount(@ModelAttribute("account") @Valid Account account, BindingResult result, RedirectAttributes redirectAttributes, HttpServletRequest request, Map<String, Object> model) {
    accountValidator.validate(account, result);

    if (result.hasErrors()) {
        redirectAttributes.addFlashAttribute("account", account);
        redirectAttributes.addFlashAttribute(BindingResult.MODEL_KEY_PREFIX + "account", result);
        return "redirect:/account/list";
    }

I can see the FlashMap in the HttpServletRequest object at the end of the addAccount method and again after the redirect in the listAccounts method. However, that map is never merged with the Model in listAccounts. If I uncomment the inputFlashMap bit in listAccounts, then I get the desired results.

Why aren't the RedirectAttributes (aka FlashMap) merged into the Model after the redirect?

Upvotes: 1

Views: 2995

Answers (3)

manuel
manuel

Reputation: 17

The method listAccounts needs @ModelAttribute("account") Account account in the params like addAccount

Upvotes: 1

axtavt
axtavt

Reputation: 242686

I think you can achieve the desired behavor by adding

@SessionAttributes("account")

to your controller instead of using flash scope. However, in this case you need to take care about removing attribute from the session when needed.

Upvotes: 0

Ralph
Ralph

Reputation: 120771

You do not need to worry about caching POST requests. Because POST requests should not been chached at all.

So it it valid to return the input form in response of an invalid POST request.

Upvotes: 0

Related Questions