SpringMVC redirect重定向傳參
阿新 • • 發佈:2019-01-06
關於SpringMVC 重定向傳參的問題一直無解,每次碰到有關需求就去網上找資料,通常情況就是問題解決了知識點就忘記了。然而網上資料太凌亂,每次都要一個個重新測試才能找到正確答案,所以這次痛下決心,記錄一下這次問題,免得下次碰到又不會,嘻嘻。
SpringMVC redirect傳參總共有3種情況,現在一一說明。
第一種:手動拼接url,當涉及到中文時會亂碼,不推薦,其他情況自己斟酌使用。
@RequestMapping(value="/get/{id}") public String get(@PathVariable int id, HttpServletRequest req, HttpServletResponse resp, ModelMap model) { return "redirect:/billManage?bill_get_id="+id; }
第二種:自動拼接url,可以使用ModelMap或者RedirectAttributes,使用這個方法位址列的url會自動新增?bill_get_id=xxx
@RequestMapping(value="/get/{id}") public String get(@PathVariable int id, HttpServletRequest req, HttpServletResponse resp, ModelMap model,RedirectAttributes attr) { attr.addAttribute("bill_get_id", id); return "redirect:/billManage"; }
第三種:不拼接url,也即url後面不新增引數,使用RedirectAttributes來實現,估計使用最多的就是這種了。當頁面重新重新整理時,引數會丟失。
重定向的controller@RequestMapping(value="/get/{id}") public String get(@PathVariable int id, HttpServletRequest req, HttpServletResponse resp, ModelMap model,RedirectAttributes attr) { attr.addFlashAttribute("bill_get_id", id); return "redirect:/billManage"; }
@RequestMapping(value="/billManage")
public String index(@ModelAttribute("bill_get_id") String billId, HttpServletRequest req, HttpServletResponse resp,
ModelMap model) {
model.addAttribute("bill_get_id", billId);
return "bill/billManage";
}
頁面可以直接使用el表示式來獲取bill_get_id的值。
var billID = '${bill_get_id}';
特別注意:通過第三種方式跳轉後,重新重新整理頁面,引數會丟失。