2012-08-09 71 views
3

在Spring MVC 3.1我可以這樣做:多次閃光的消息在Spring MVC

@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"; 
} 

然後顯示在查看Flash消息:

<p>${flashSuccessMsg}</p> 

但我寧願有閃光的列表消息,然後在視圖中對此進行迭代。

這可能嗎?

如果我這樣做:redirectAttributes.addFlashAttribute("Update Successful"); 即我沒有命名的Flash消息,然後如何在視圖中回收它?

回答

8

您是否嘗試過使用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"; 
} 

後來,在你看來,你可以在messages使用<c:foreach />標籤重複:

<c:foreach items="${messages}"> 
... 
</c:foreach> 
+0

這是一個解決方案,但可能有多種方法調用addFlashAttribute。我希望避免必須手動使用列表。 – Mark 2012-08-09 13:26:46

+1

@Mark這是*正確的*答案。 – 2013-02-25 18:02:36

+0

@Mark你能幫我瞭解其他方法嗎? – kamal 2016-12-11 07:31:01