写的很是详细,参看该地址: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 }