springMVC controller間跳轉 重定向 傳遞參數的方法


springMVC controller間跳轉 重定向 傳遞參數的方法

spring MVC框架controller間跳轉,需重定向。有幾種情況:不帶參數跳轉,帶參數拼接url形式跳轉,帶參數不拼接參數跳轉,頁面也能顯示。
常用的方法:
(1)從一個controller中的方法跳轉到另一個controller中的方法不需要傳遞參數
方式一:使用ModelAndView
return new ModelAndView(“redirect:/toList”);
這樣可以重定向到另一個controller的toList這個方法
方式二:返回String
return “redirect:/ toList “;
這是不帶參數的重定向。
( 2)第二種情況,需要攜帶參數時參數可以拼接url
方式一:自己手動拼接url
new ModelAndView(“redirect:/toList?param1=”+value1+”&param2=”+value2);
這樣有個弊端,就是傳中文可能會有亂碼問題。
方式二:用RedirectAttributes,這個是發現的一個比較好用的一個類 , SpringMVC 自己的類
這里用它的addAttribute方法,這個實際上重定向過去以后你看url,是它自動給你拼了你的url。
使用方法:
public String save(RedirectAttributes attr)
attr.addAttribute(“param”, value);
return “redirect:/namespace/toController”;
這樣在toController這個方法中就可以通過獲得參數的方式獲得這個參數,再傳遞到頁面。過去的url還是和方式一
一樣的。
獲得參數的方式:
request.getParameter(“productActivityId”);
(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”, “添加出錯”);
return “redirect:/maintenance/toAddConfigCenter”;
}
}
addFlashAttribute() springMVC3中 該方法將信息放到session中,在頁面直接用el表達式就可以獲得.session在跳到頁面后
馬上移除對象。所以你刷新一下后這個值就會丟掉。
總結
本質還是兩次跳轉,spring進行了封裝;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM