2014-09-01 71 views
0

閃光燈和型號屬性有什麼不同?閃光燈屬性與型號屬性

我想存儲一個對象並將其顯示在我的jsp中,並在其他控制器中重新使用它。我使用sessionAttribute,它在jsp中工作正常,但問題是當我嘗試在其他控制器中檢索model屬性時。

我失去了一些數據。我四處搜索,發現flash attribute允許將過去的值傳遞給不同的控制器,不是嗎?

回答

1

如果我們想通過attributes via redirect between two controllers,我們不能用request attributes(他們將無法生存重定向),我們不能使用Spring的(因爲春天處理它的方式)@SessionAttributes,只能使用一個普通的HttpSession,這不是很方便。

Flash屬性爲一個請求提供了一種方法,用於存儲用於另一個請求的屬性。這是重定向時最常需要的 - 例如Post/Redirect/Get模式。在重定向(通常在會話中)之前,Flash屬性會臨時保存,以便在重定向後立即將其刪除。

Spring MVC有兩個支持flash屬性的主要抽象。 FlashMap用於保存閃存屬性,而FlashMapManager用於存儲,檢索和管理FlashMap實例。

@Controller 
@RequestMapping("/foo") 
public class FooController { 

    @RequestMapping(value = "/bar", method = RequestMethod.GET) 
    public ModelAndView handleGet(Model model) { 
    String some = (String) model.asMap().get("some"); 
    // do the job 
} 

    @RequestMapping(value = "/bar", method = RequestMethod.POST) 
    public ModelAndView handlePost(RedirectAttributes redirectAttrs) { 
    redirectAttrs.addFlashAttributes("some", "thing"); 
    return new ModelAndView().setViewName("redirect:/foo/bar"); 
    } 

} 

在上面的例子中,請求到達handlePostflashAttributes相加,和在handleGet方法retrived。

更多信息herehere