關於SpringMVC中的轉發與重定向的說明


寫的非常詳細,參看該地址:https://www.zifangsky.cn/661.html

總結:

1.請求轉發:url地址不變,可帶參數,如?username=forward

2.請求重定向:url地址改變,在url上帶參數無效。具體可以使用四種傳參方式:

a.使用sesssion,b.使用RedirectAttribute類,c.使用@ModelAttribute注解,d.使用RequestContextUtils類(推薦使用后面兩中)

參考:

轉發:一次請求,服務器內部調用另外的組件處理,request和response可以共用,有限制性,只能轉發到本應用中的某些資源,頁面或者controller請求,可以訪問WEB-INF目錄下面的頁面

重定向:兩次請求,地址會改變,request和response不能共用,不能直接訪問WEB-INF下面的資源,

根據所要跳轉的資源,可以分為跳轉到頁面或者跳轉到其他controller

 

實例代碼(在springboot下測試的)如下:

 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM