解決方法
我在後臺一個controller跳轉到另一個controller,爲什麼有這種需求呢,是這樣的。我有一個列表頁面,然後我會進行新增操作,新增在後臺完成之後我要跳轉到列表頁面,不需要傳遞參數,列表頁面默認查詢所有的。
- 方式一:使用ModelAndView
return new ModelAndView(“redirect:/toList”);
這樣可以重定向到toList這個方法 - 方式二:返回String
return “redirect:/ toList “;
其它方式:其它方式還有很多,這裏不再做介紹了,比如說response等等。這是不帶參數的重定向。
- 方式一:使用ModelAndView
第二種情況,列表頁面有查詢條件,跳轉後我的查詢條件不能丟掉,這樣就需要帶參數的了,帶參數可以拼接url
方式一:自己手動拼接url
new ModelAndView("redirect:/toList? param1="+value1+"¶m2="+value2);
這樣有個弊端,就是傳中文可能會有亂碼問題。
方式二:用RedirectAttributes,這個是發現的一個比較好用的一個類
這裏用它的addAttribute方法,這個實際上重定向過去以後你看url,是它自動給你拼了你的url。
使用方法:
attr.addAttribute("param", value);
return "redirect:/namespace/toController";
這樣在toController這個方法中就可以通過獲得參數的方式獲得這個參數,再傳遞到頁面。過去的url還是和方式一一樣的。
- 帶參數不拼接url頁面也能拿到值(重點是這個)
一般我估計重定向到都想用這種方式:
@RequestMapping("/save")
public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)throws Exception {
String code = service.save(form);
if(code.equals("000")){
attr.addFlashAttribute("name", form.getName());
attr.addFlashAttribute("success", "添加成功!");
return "redirect:/index";
}else{
attr.addAttribute("projectName", form.getProjectName());
attr.addAttribute("enviroment", form.getEnviroment());
attr.addFlashAttribute("msg", "添加出錯!錯誤碼爲:"+rsp.getCode().getCode()+",錯誤爲:"+rsp.getCode().getName());
return "redirect:/maintenance/toAddConfigCenter";
}
}
@RequestMapping("/index")
public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)
throws Exception {
return "redirect:/main/list";
}
頁面取值不用我說了吧,直接用el表達式就能獲得到,這裏的原理是放到session中,session在跳到頁面後馬上移除對象。所以你刷新一下後這個值就會丟掉。