Controller之間的重定向

Java中原生的重定向和請求轉發
重定向:response.sendRedirect(url) 如果有參數,就只將參數拼接在url 上
請求轉發:request.getRequestDispatcher(url).forward(request,response) 請求轉發的參數一般存放在request 域中

在spring 中提供的重定向的方式(當然可以使用原生的重定向)主要介紹帶參的重定向
1. 將參數放在Model 中

public String Test(Model model){
    int id =5;
	model.addAttributes("id",id);
	return "redirect:/user/{id}";
}
這樣傳遞的URL:/user/5
目標Controller 接收參數:
@GetMapping("/user/{id}")
public void ToController(Model model,@PathVariable("id") Interget id){.....}
很遺憾的是:測試失敗報錯model 中沒有“id”  尚待解決

Model:可以作爲controller 的入參,同時可以向頁面傳遞數據(在有引擎模板的時候在頁面中使用el 語句獲取裏面的值)本質上數據是保存在session 中的;

數據的領域模型也叫做Model:這是一個抽象的概念

2. 直接將數據拼接在URL後面

return “redirect:/user?id =”+id;
直接拼接參數在遇到中文是會出錯
嚴謹一點不是很建議這樣使用

3. 使用一個特別好用的類RedirectAttributes

public String Test(RedirectAttributes att){
	int id = 5;
	att.addAttriutes("id",id);
	return "redirect:/user";
}
URL:/user?id =5
目標Controller接收數據
@Get Mapping("/user")
public void toController(@RequestParam("id") Integer id,HttpServletResponse response ){.....}

這裏有一個細節要注意:如果重定向的 目標Controller 沒有返回值(void ) 參數列表裏面一定要加:HttpServletResponse response 不然就會報錯
RedirectAttributes 還有一個方法:addFlashAttributes(key,value);
addFlashAttributes 的用法:

1. 向頁面傳遞數據:本質上市存放在session 中的,在頁面使用el 表達式獲取相應的數據
2. 用於傳遞數據:數據會被隱【接收的方式還是get但是數據會被隱藏】
 att.addFlashAttribute("id",x);
 return "redirect:/tget";
 接收:
 @GetMapping("/tget")
  public void  TargetTest(@ModelAttribute("id")Integer id, HttpServletResponse response){ }
 
  1. 使用ModelAndView
public ModelAndView Test(){
	return new ModelAndView(url )  如果有參數直接拼接在url 上面
}
拼接的URL:/user?id = 5;
接收:
@RequestParam("id")
好處:不受@ResponseBody 的限制。當返回類型爲String時就不能有註解@ResponseBody

重定向基本是get 方式,目標Controller 怎麼接收參數取決於起始Controller是怎麼將參數傳過去的:

1. 字符串拼接:?–@RequestParam()
2. 佔位/{id} --@PathVariable()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章