Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple flash messages in Spring MVC

Tags:

spring-mvc

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?

like image 338
Mark Avatar asked Nov 18 '25 20:11

Mark


1 Answers

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>
like image 151
jelies Avatar answered Nov 21 '25 08:11

jelies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!