Controller 之間的跳轉

在開發中,有時會遇到 controller 之間跳轉的狀況,並且有時在跳轉的時候須要把不一樣的參數傳遞過去,好比從controller a跳轉到controller b,再從controller b到前端頁面,而且把controller a裏的數據好比StringListMap或者對象傳遞到頁面,等等相似狀況。結合查找網上的資料以及本身的試驗,現總結以下。html

注: 本文實例均在springmvc框架下,其餘架構自行調整。前端


1、跳轉方式

1. forward

使用返回 String 的方式: return "forward:Xxx.action";java

@RequestMapping("/index")
public String logout(ModelMap model, RedirectAttributes attr) {
	return "forward:test.action";
}

若是使用ModelAndView方式: return new ModelAndView("forward:/tolist");ajax

:此後,都以返回String的方式來敘述。spring

2. redirect

@RequestMapping("/index")
public String logout(ModelMap model, RedirectAttributes attr) {
	return "redirect:test.action";
}

3. forward 和 redirect 比較

**forward**是請求轉發,是服務器端行爲,至關於一次請求,地址欄的 URL 不會改變。 **redirect**是請求重定向,是客戶端行爲,至關於兩次請求,地址欄的 URL 會改變。安全

2、跳轉時數據的傳遞

1. 方式一:手動拼接 URL

return "redirect:/login.action?name="+ name;

login.action:服務器

@RequestMapping("/login")
	public String login(HttpServletRequest request, ModelMap model, RedirectAttributes attr ) {
       String name = request.getParameter("name");
	   model.addAttribute("name",name);
	   return "login";
	}

而後在login.html接收,用${name}便可。session

拼接url傳參的缺點:架構

  • 參數包含中文字符的話,容易出現問題
  • 不能

2. 方式二:RedirectAttributes

RedirectAttributes 是 Spring mvc 3.1 版本以後出來的一個功能,專門用於重定向以後還能帶參數跳轉的的工具類。 它有兩種帶參的方式:mvc

第一種:redirectAttributes.addAttributie("prama",value);

redirectAttributes.addAttribute("prama1",value1);
redirectAttributes.addAttribute("prama2",value2);
return:"redirect:/path/list"

這種方法至關於在重定向連接地址追加傳遞的參數:return:"redirect:/path/list?prama1=value1&prama2=value2(直接追加參數會將傳遞的參數暴露在連接的地址上,很是的不安全,慎用)

第二種:redirectAttributes.addFlashAttribute("prama",value);

redirectAttributes.addFlashAttribute("prama1",str);
redirectAttributes.addFlashAttribute("prama2",list);
redirectAttributes.addFlashAttribute("prama3",map);
return:"redirect:/path/list.jsp" ;

此方法隱藏了參數,連接地址上不直接暴露,可是能且只能在重定向的頁面上獲取prama的值。其原理是參數放到了sessionsession在跳轉以後立刻移除對象。若是重定向到一個controller,是取不到該prama的值的。


總的來講,controller之間跳轉而後把參數傳到前臺頁面,這種方式實現起來費力不討好,對於數據傳遞以及前臺頁面的接收展現來講不是很友好,其實能夠換成用ajax方式來作,調用後臺數據更加靈活而且局部刷新功能也更加友好。But,多一種方式,多一種選擇。

相關文章
相關標籤/搜索