Spring mvc Controller間跳轉/重定向/傳參
阿新 • • 發佈:2019-01-22
Spring mvc Controller常用寫法
1.ModelAndView
@RequestMapping(value = "/getxxxList.html")
public ModelAndView getxxxList(XxxDTO xxxDTO,WebPage webPage){
//ModelAndView modelAndView = new ModelAndView("/xxx/xxxList");//跳轉
ModelAndView modelAndView = new ModelAndView("redirect:/xxx/xxxList");//重定向
try {
//檢索引數回顯
modelAndView.addObject("xxxDTO",xxxDTO);
//執行查詢
modelAndView.addObject("xxxList",xxxList);
}catch (Exception e){
e.printStackTrace();
}
return modelAndView;
}
2.String
@RequestMapping(value = "/getxxxList.html")
public String getxxxList(XxxDTO xxxDTO,WebPage webPage,Model model){
try {
//檢索引數回顯
model.addAttribute("xxxDTO",xxxDTO);
//執行查詢
model.addAttribute("xxxList",xxxList);
}catch (Exception e){
e.printStackTrace();
}
//return "/xxx/xxxList";//跳轉
return "redirect:/xxx/xxxList";//重定向
}
返回地址引數拼接
1.手動拼接URL
"redirect:/xxx/xxxList?param1=" +value1+"¶m2="+value2"
2-1.使用RedirectAttributes自動拼接重定向URL
@RequestMapping(value = "/getxxxList.html")
public String getxxxList(RedirectAttributes redirectAttributes){
redirectAttributes.addAttribute("param1", value1);
redirectAttributes.addAttribute("param2", value2);
return "redirect:/xxx/toController";//重定向
}
Tip:曾經在專案中遇到過很詭異的重定向問題,業務程式碼執行無錯無異常並且順利到達 return,重定向結果就是頁面報錯500,後臺並未有異常丟擲,且在眾多Controller方法中,只有兩三個Controller方法遇到了這樣的問題,使用RedirectAttributes後解決了這個重定向異常的問題。
2-2.使用RedirectAttributes的addFlashAttribute方法
@RequestMapping("/save")
public String save(@ModelAttribute("form") XxxBean 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:/xxx/toController";
}
}
注意:
- 在2-1中使用addAttribute方法傳參,引數會自動拼接在URL後面,而使用addFlashAttribute方法會把引數值暫存於session,待重定向URL獲取該引數後從session中移除,這裡的redirect必須是方法對映路徑,jsp無效。重定向後引數值只會出現一次,重新整理頁面後不再出現。
- 如果使用了RedirectAttributes作為引數,但是沒有進行redirect,這種情況下不會將RedirectAttributes引數進行傳遞,預設還是傳遞forward對應的model,官方的建議是可以設定RequestMappingHandlerAdapter的ignoreDefaultModelOnRedirect屬性,這樣可以提高效率,避免不必要的檢索。