SpringMVC 重定向參數 RedirectAttributes

SpringMVC 中常用到 redirect 來實現重定向。但使用場景各有需求,如果只是簡單的頁面跳轉顯然無法滿足所有要求,比如重定向時需要在 url 中拼接參數,或者返回的頁面需要傳遞 Model。SpringMVC 用 RedirectAttributes 解決了這兩個需要。

首先,在 Controller 中做 redirect 中可用如下方式實現:
return new ModelAndView(“redirect:/index”);

return “redirect:/index”;

此時,如果只是重定向至某一 URL 或者比較簡單地址,也可以不用 RedirectAttributes,直接拼接,如:return “redirect:/index?param1=value1″;

但是這樣似乎有點過於簡單粗暴,而且參數多了很容易使代碼可讀性變差。使用 RedirectAttributes 來設置重定向頁面的參數,SpringMVC 會自動拼接 url。接下來主要介紹該對象的兩個方法:

1. addAttribute

@RequestMapping("/save")
public String save(User user, RedirectAttributes redirectAttributes) {
    redirectAttributes.addAttribute("param", "value1");
    return "redirect:/index";
}

請求 /save 後,跳轉至/index,並且會在url拼接 ?param=value1。

2. addFlashAttribute

@RequestMapping("/save")
public String save(User user, RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute("param", "value1");
    return "redirect:/index";
}

請求 /save 後,跳轉至 /index,並且可以在 index 對應的模版中通過表達式,比如 jsp 中 jstl 用 ${param},獲取返回值。該值其實是保存在 session 中的,並且會在下次重定向請求時刪除。

RedirectAttributes 中兩個方法的簡單介紹就是這樣。

轉載:http://blog.csdn.net/z69183787/article/details/52596987

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章