一、重定向:重定向是客戶端行為,在使用時,務必使用全路徑,否則可能因為外部環境導致錯誤
1、URL改變為重定向的URL地址
2、前台頁面不能使用Ajax請求提交, 應該使用form表單提交
方法一、參數URL
return new RedirectView("https://www.baidu.com")
方法二、參數URL
return "redirect:https://www.baidu.com";//協議類型一定要有
return "redirect:/home";
方法三、參數URL
response.sendRedirect("https://www.baidu.com");
方法四、參數view、viewName
return new ModelAndView("redirect:https://www.baidu.com")
3、參數傳遞
方法一、直接在url后面拼接參數,使用@RequestParam來取值,不推薦使用
方法二、在controller方法的參數中使用RedirectAttributes來傳遞參數;在跳轉的controller中同樣使用@RequestParam來取值,在瀏覽器中同樣是拼接參數的形式
public String redirect(RedirectAttributes attr) { attr.addAttribute("name", "zhangsan"); return "redirect:/home"; }
方法三、使用RedirectAttributes的addFlashAttribute的方法來設置值,原理是在跳轉前將值放入session中,跳轉之后就將值清除掉。瀏覽器的地址不顯示參數的值,推薦使用這種方法來傳值。
attr.addFlashAttribute("name", "zhangsan");
重定向的方法中取值:@ModelAttribute("name") String name, 前台頁面中無法取到該值
二、轉發,服務器行為相對路徑沒有問題
1、地址欄不會改變
2、轉發前后,后邊的控制器繼承前邊控制器的請求參數(前邊的控制器中改變參數,后邊控制器看到的參數是更改后的參數)
3、攔截器只攔截一次請求
4、轉發會在后台執行多個控制器
方法一、
return "forward:/dengluPost";
方法二、參數URL
request.getRequestDispatcher("/dengluPost").forward(request,response);
方法三、參數view、viewName
return new ModelAndView("forward:/dengluPost")
三、知識點
1、單系統, 經過重定向、轉發的請求 sessionId 不變
2、