在開(kāi)發(fā)中,有時(shí)會(huì)遇到 controller 之間跳轉(zhuǎn)的情況,而且有時(shí)在跳轉(zhuǎn)的時(shí)候需要把不同的參數(shù)傳遞過(guò)去,比如從controller a跳轉(zhuǎn)到controller b,再?gòu)?code>controller b到前端頁(yè)面,并且把controller a里的數(shù)據(jù)比如String、List、Map或者對(duì)象傳遞到頁(yè)面,等等類(lèi)似情況。結(jié)合查找網(wǎng)上的資料以及自己的試驗(yàn),現(xiàn)總結(jié)如下。
注: 本文實(shí)例均在springmvc框架下,其他架構(gòu)自行調(diào)整。
跳轉(zhuǎn)方式
forward
使用返回 String 的方式: return "forward:Xxx.action";
@RequestMapping("/index")
public String logout(ModelMap model, RedirectAttributes attr) {
return "forward:test.action";
}
如果使用ModelAndView方式: return new ModelAndView("forward:/tolist");
注:此后,都以返回String的方式來(lái)敘述。
redirect
@RequestMapping("/index")
public String logout(ModelMap model, RedirectAttributes attr) {
return "redirect:test.action";
}
forward 和 redirect 比較
forward是請(qǐng)求轉(zhuǎn)發(fā),是服務(wù)器端行為,相當(dāng)于一次請(qǐng)求,地址欄的 URL 不會(huì)改變。
redirect是請(qǐng)求重定向,是客戶端行為,相當(dāng)于兩次請(qǐng)求,地址欄的 URL 會(huì)改變。
跳轉(zhuǎn)時(shí)數(shù)據(jù)的傳遞
方式一:手動(dòng)拼接 URL
return "redirect:/login.action?name="+ name;
login.action:
@RequestMapping("/login")
public String login(HttpServletRequest request, ModelMap model, RedirectAttributes attr ) {
String name = request.getParameter("name");
model.addAttribute("name",name);
return "login";
}
然后在login.html接收,用${name}即可。
拼接url傳參的缺點(diǎn):
- 參數(shù)包含中文字符的話,容易出現(xiàn)問(wèn)題
- 不能
方式二:RedirectAttributes
RedirectAttributes 是 Spring mvc 3.1 版本之后出來(lái)的一個(gè)功能,專(zhuān)門(mén)用于重定向之后還能帶參數(shù)跳轉(zhuǎn)的的工具類(lèi)。
它有兩種帶參的方式:
第一種:redirectAttributes.addAttributie("prama",value);
redirectAttributes.addAttribute("prama1",value1);
redirectAttributes.addAttribute("prama2",value2);
return:"redirect:/path/list"
這種方法相當(dāng)于在重定向鏈接地址追加傳遞的參數(shù):return:"redirect:/path/list?prama1=value1&prama2=value2(直接追加參數(shù)會(huì)將傳遞的參數(shù)暴露在鏈接的地址上,非常的不安全,慎用)
第二種:redirectAttributes.addFlashAttribute("prama",value);
redirectAttributes.addFlashAttribute("prama1",str);
redirectAttributes.addFlashAttribute("prama2",list);
redirectAttributes.addFlashAttribute("prama3",map);
return:"redirect:/path/list.jsp" ;
此方法隱藏了參數(shù),鏈接地址上不直接暴露,但是能且只能在重定向的頁(yè)面上獲取prama的值。其原理是參數(shù)放到了session中,session在跳轉(zhuǎn)之后馬上移除對(duì)象。如果重定向到一個(gè)controller,是取不到該prama的值的。
總的來(lái)說(shuō),controller之間跳轉(zhuǎn)然后把參數(shù)傳到前臺(tái)頁(yè)面,這種方式實(shí)現(xiàn)起來(lái)費(fèi)力不討好,對(duì)于數(shù)據(jù)傳遞以及前臺(tái)頁(yè)面的接收展示來(lái)說(shuō)不是很友好,其實(shí)可以換成用ajax方式來(lái)做,調(diào)用后臺(tái)數(shù)據(jù)更加靈活并且局部刷新功能也更加友好。But,多種方式,多種選擇。