请求重定向的作用是将请求,重定向至另外一个处理程序。它的特点是两次请求,浏览器地址会改变,用户可以感知
转发操作,可以使用ModelAndView对象
return new ModelAndView("redirect:viewName",modelMap);
也可以直接返回字符串视图名
return "redirect:viewName";
当重定向需要携带参数时可以使用RedirectAttributes
package com.example.redirect.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class HelloController { @RequestMapping("hello/{name}") public String hello(@PathVariable String name, RedirectAttributes redirectAttributes){ System.out.println("hello,"+name); redirectAttributes.addFlashAttribute("name",name); return "redirect:/welcome/{name}"; } }
另一个控制器
package com.example.redirect.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class WelcomController { @RequestMapping("welcome/{name}") @ResponseBody public String welcome(@PathVariable String name){ System.out.println("welcome,"+name); return "welcome,"+name; } }
使用addFlashAttribute方法把需要的参数添加进去
在转发的控制器依然可以拿到路径参数
addFlashAttribute和addAttribute的区别是,前者实际是把信息存在用户的session里,然后在下次请求前删除参数,路径中看不到参数;后者是把参数添加在请求中,再进行重定向——参数会被添加在url里
例如:
原请求
http://localhost:8080/hello?name=123
重定向后
http://localhost:8080/welcome?name=123
在使用路径参数时不能从路径中看出差别
不使用路径参数时addFlashAttribute添加的参数,在控制器中使用@ModelAttribute注解得到
@RequestMapping("hello") public String hello(String name, RedirectAttributes redirectAttributes){ System.out.println("hello,"+name); redirectAttributes.addFlashAttribute("name",name); // redirectAttributes.addAttribute("name",name); return "redirect:/welcome"; }
@RequestMapping("welcome") @ResponseBody public String welcome(@ModelAttribute("name") String name){ System.out.println("welcome,"+name); return "welcome,"+name; }
使用addAttribute添加的参数,依然使用@RequestParam获取