摘自http://elf8848.iteye.com/blog/875830
(1)我在后台一個controller跳轉到另一個controller,為什么有這種需求呢,是這樣的。我有一個列表頁面,然后我會進行新增操作,新增在后台完成之后我要跳轉到列表頁面,不需要傳遞參數,列表頁面默認查詢所有的。
方式一:使用ModelAndView
return new ModelAndView("redirect:/toList");
這樣可以重定向到toList這個方法
方式二:返回String
return "redirect:/ toList ";
(2)第二種情況,列表頁面有查詢條件,跳轉后我的查詢條件不能丟掉,這樣就需要帶參數的了,帶參數可以拼接url
方式一:自己手動拼接url
new ModelAndView("redirect:/toList?param1="+value1+"¶m2="+value2);
這樣有個弊端,就是傳中文可能會有亂碼問題。
方式二:用RedirectAttributes,這個是發現的一個比較好用的一個類
這里用它的addAttribute方法,這個實際上重定向過去以后你看url,是它自動給你拼了你的url。
使用方法:
attr.addAttribute("param", value);
return "redirect:/namespace/toController";
這樣在toController這個方法中就可以通過獲得參數的方式獲得這個參數,再傳遞到頁面。過去的url還是和方式一一樣的。
(3)帶參數不拼接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在跳到頁面后馬上移除對象。所以你刷新一下后這個值就會丟掉。
3. 總結
最底層還是兩種跳轉,只是spring又進行了封裝而已,所以說跳轉的方式其實有很多很多種,你自己也可以封一個,也可以用最原始的response來,也沒有問題。好了,就到這兒。
springmvc參考開發文檔http://www.boyunjian.com/javadoc/org.springframework/spring-webmvc/4.0.5.RELEASE/_/org/springframework/web/servlet/view/JstlView.html