2

I have the following situation in my MVC controller

    for (String key : form.keySet())
        redirectAttrs.addFlashAttribute(key, form.getFirst(key));

    return "redirect:" + page;

page is /secure/admin/pages/userPreferences.jsp and I have a single username attribute added to the flash attributes

From the JSP page, how do I access that username flash attributes. But I have no idea of how!

I have tried both ${param.username} and ${username} but none worked. I tried to dump all ${param} and request attributes but found nothing in the JSP

Similar question: How to read flash attributes after redirection in Spring MVC 3.1? - the difference is that they want to read flash attributes from MVC controller rather than from JSP view

usr-local-ΕΨΗΕΛΩΝ
  • 26,101
  • 30
  • 154
  • 305

2 Answers2

2

Workaround: if I use redirectAttrs.addAttribute instead of addFlashAttribute I get two effects:

  1. JSP page will see ${param.username} and act accordingly
  2. I get that username in the query string (e.g. userPreferences.jsp?username=jdoe) which is not really exciting, but actually allows refreshing the page

This is a workaround because I preferred to have parameters invisible - which is the main reason one uses flash attributes.

usr-local-ΕΨΗΕΛΩΝ
  • 26,101
  • 30
  • 154
  • 305
  • This worked for me to get the value in the JSP!! Thanks! But what's the difference between `addAttribute` and `addFlashAttribute` ? – gene b. Dec 14 '21 at 19:08
2

If you redirect, the other controller will be called.

What you can do is to transfer the flashed Arguments as a normal model attributes:

@RequestMapping(method = RequestMethod.GET)
protected String get(HttpServletRequest request, Model model) { // redirect request

    Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
    if (inputFlashMap != null) {
        String name = (String) inputFlashMap.get("username");
        model.addAttribute("username", name);
    }

    return "page";
}

The other option is to access the flash map in your jsp. Look at this implementation of :

public static Map<String, ?> getInputFlashMap(HttpServletRequest request) {
    return (Map<String, ?>) request.getAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE);
}

with:

public static final String INPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".INPUT_FLASH_MAP";

unfortunately the dot in the attribute name do not allow you to access the map directly. You will have to do it by using <% code %>

alex
  • 8,904
  • 6
  • 49
  • 75