在servlet中,转发和重定向是由request和response完成的。两者之间的区别请看我之前的文章。那么在springMVC中是如何完成的呢?
/转发/
@RequestMapping(“/login.do”)
public String login(HttpServletRequest request,HttpServletResponse response){
request.setAttribute(“message”, “hello”);
return “forward:/index.do”; //forward在跳转后可以取到message值
index.do为另外一个path,也就是RequestMapping中的值。
@RequestMapping(“/index.do”)
public String index(HttpServletRequest request,HttpServletResponse response){
return “welcome”;
/重定向/
@RequestMapping(“/logout.do”)
public String logout(HttpServletRequest request,HttpServletResponse response){
request.setAttribute(“message”, “hello”);
return “redirect:/register.do”; //redirect在跳转后无法取到message值
register.do为另外一个path,也就是RequestMapping中的值。
@RequestMapping(“/register.do”)
return “register”;
另外forward跳转后地址栏URL不会改变 而redirect会改变
当我们使用重定向时,在后台传到页面的参数全部丢失,除非放在session中。所以在springMVC有一种解决方式如下:
@RequestMapping(“/update.do”)
public String update( RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute(“message”, “操作成功”);
return “redirect:/admin/user”;
在重定向的页面中,可以获取到message的值,这是由于spring将message放入session中了。
Original: https://www.cnblogs.com/machine-matrix/p/7010589.html
Author: liandyao
Title: SpringMVC转发和重定向区别!
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/592294/
转载文章受原作者版权保护。转载请注明原作者出处!