简体   繁体   中英

How do I preserve model flash attributes on multiple redirects

Suppose I have a controller method for viewing a customer, if they do not have access to view that customer an error message is to be added as a flash attribute then redirect to a territory listing, however; if the user is assigned a single territory then the territory handler method redirects to a customer listing within that territory.

@RequestMapping("/customers/{id}")
public ModelAndView customers(@PathVariable("id") long id,
                              Principal principal,
                              RedirectAttributes ra) {
    // if user is not allowed
    if (!svc.isAccessGrantedToCustomer(principal.getName(), id)) {
        ra.addFlashAttribute("errorMessage",
                             "Access denied for customer " + id + ".");
        return new ModelAndView("redirect:/territories");
    }
    // get customer and return new view...
}

@RequestMapping("/territories")
public ModelAndView territories(Principal principal,
                                RedirectAttributes ra) {
    // get some territory for user.
    Long id = svc.getUserTerritory(principal.getName());
    if (id != null) {
        return new ModelAndView("redirect:/territories/" + id);
    }
    // return new view.
}

@RequestMapping("/territories/{id}")
public ModelAndView territory(@PathVariable("id") long id,
                              Principal principal,
                              ModelAndView mav,
                              Model m,
                              RedirectAttributes ra) {
    // mav is empty, it does not contain flash attributes.
    // m does contain flash attributes.
    // Fill model and return view.
    mav.setViewName("territory");
    // fill the model...
    return mav;
}

All redirects work as expected, however the model attributes are lost.

What I have found is that the model attributes are present in Model .

One solution is to re-add all flash attributes from the Model to the RedirectAttribute , however; this seems ill required and actually adds more than I want.

m.asMap().forEach((k, v) -> ra.addFlashAttribute(k, v));

IMHO a handler shouldn't be worrying about how it got invoked (redirected, direct) so should not have to re-add flash attributes.

You can use @SessionAttributes on controller level

Look here for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM