寫的很是詳細,參看該地址:https://www.zifangsky.cn/661.htmlhtml
總結:spring
1.請求轉發:url地址不變,可帶參數,如?username=forwardapi
2.請求重定向:url地址改變,在url上帶參數無效。具體可使用四種傳參方式:springboot
a.使用sesssion,b.使用RedirectAttribute類,c.使用@ModelAttribute註解,d.使用RequestContextUtils類(推薦使用後面兩中)服務器
參考:app
轉發:一次請求,服務器內部調用另外的組件處理,request和response能夠共用,有限制性,只能轉發到本應用中的某些資源,頁面或者controller請求,能夠訪問WEB-INF目錄下面的頁面測試
重定向:兩次請求,地址會改變,request和response不能共用,不能直接訪問WEB-INF下面的資源,url
根據所要跳轉的資源,能夠分爲跳轉到頁面或者跳轉到其餘controllerspa
實例代碼(在springboot下測試的)以下:
code
1 /**
2 * @Author Mr.Yao 3 * @Date 2019/5/5 10:22 4 * @Content SpringBootStudy 5 */
6 @Controller 7 public class ForwardAndRedirectController { 8 @RequestMapping("/test/index") 9 public ModelAndView userIndex() { 10 System.out.println("進入userIdex了"); 11 ModelAndView view = new ModelAndView("index"); 12 view.addObject("name","向html頁面中設值。"); 13 return view; 14 } 15
16 //使用forward
17 @RequestMapping("/testForward.html") 18 public ModelAndView testForward(@RequestParam("username") String username){ 19
20 System.out.println("test-forward....."+username); 21 ModelAndView mAndView = new ModelAndView("forward:/test/index"); 22
23 User user = new User(); 24 user.setName(username); 25 mAndView.addObject("user", user); 26 return mAndView; 27 } 28 //使用servlet api
29 @RequestMapping(value="/test/api/{name}") 30 public void test(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) throws Exception { 31 System.out.println("使用servlet api中的方法。。。"+name); 32 request.getRequestDispatcher("/test/index").forward(request, response); 33 } 34
35 //使用redirect
36 @RequestMapping("/testRedirect.html") 37 public ModelAndView testRedirect(@RequestParam("username") String username){ 38 ModelAndView mAndView = new ModelAndView("redirect:/redirect/index"); 39 System.out.println("test-redirect....."+username); 40 User user = new User(); 41 user.setName(username); 42 mAndView.addObject("user", user); 43 mAndView.addObject("name", "hello world"); 44 return mAndView; 45 } 46 @RequestMapping("/redirect/index") 47 public ModelAndView indexRedirect(@ModelAttribute("user") User user, @ModelAttribute("name") String name) { 48
49 System.out.println(name +"====經過重定向過來的,獲取參數值:"+user.getName()); 50 return new ModelAndView("index"); 51 } 52 //使用servlet api 中重定向,responese.sendRedirect()
53 }