3

In Spring MVC 3.1 I can do:

@RequestMapping(value = "{id}/edit", method = RequestMethod.POST)
public String update(Category category, @PathVariable Integer id, 
    @RequestParam("childrenOrder") int[] childrenOrder,
    RedirectAttributes redirectAttributes) {

    if (!id.equals(category.getCategoryId())) throw new IllegalArgumentException("Attempting to update the wrong category");
    categoryMapper.updateByPrimaryKey(category);
    redirectAttributes.addFlashAttribute("flashSuccessMsg", "Update Successful");  //ADD FLASH MESSAGE
    return "redirect:/admin/categories.html";
}

And then show the flash message in the view:

 <p>${flashSuccessMsg}</p>

But I would rather have a list of flash messages, and then iterate over this in the view.

Is this possible?

If I do: redirectAttributes.addFlashAttribute("Update Successful"); i.e. I don't name the flash message, how do I then retrive it in the view?

1 Answer 1

8

Have you tried using RedirectAttributes addFlashAttribute(String attributeName, Object attributeValue)?

@RequestMapping(value = "{id}/edit", method = RequestMethod.POST)
public String update(Category category, @PathVariable Integer id, @RequestParam("childrenOrder") int[] childrenOrder, RedirectAttributes redirectAttributes) {
    if (!id.equals(category.getCategoryId())) throw new IllegalArgumentException("Attempting to update the wrong category");
    categoryMapper.updateByPrimaryKey(category);

    List<String> messages = new ArrayList<String>();
    // populate messages 

    redirectAttributes.addFlashAttribute("messages", messages);  

    return "redirect:/admin/categories.html";
}

Later, in your view you can iterate over messages using a <c:foreach /> tag:

<c:foreach items="${messages}">
...
</c:foreach>
2
  • That is one solution, but there might be multiple methods calling addFlashAttribute. I was hoping to avoid having to do it manually with lists.
    – Mark
    Commented Aug 9, 2012 at 13:26
  • @Mark Can you help me to know what are other ways?
    – kamal
    Commented Dec 11, 2016 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.