简单谈谈SpringMVC转发和重定向的区别
在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") public String register(HttpServletRequest request,HttpServletResponse response){ 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中了。
以上这篇简单谈谈SpringMVC转发和重定向的区别就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Springboot基于Redisson实现Redis分布式可重入锁源码解析
这篇文章主要介绍了Springboot基于Redisson实现Redis分布式可重入锁,本文通过案例源码分析给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-03-03深入了解Spring中的@Autowired和@Resource注解
Spring中的@Autowired和@Resource注解都可以实现依赖注入,但使用方式、注入策略和适用场景略有不同。本文将深入探讨这两种注解的原理、使用方法及优缺点,帮助读者更好地理解和运用Spring依赖注入机制2023-04-04Java调度线程池ScheduledThreadPoolExecutor不执行问题分析
最近项目上反馈某个重要的定时任务突然不执行了,很头疼,开发环境和测试环境都没有出现过这个问题。定时任务采用的是ScheduledThreadPoolExecutor,后来一看代码发现踩了一个大坑。本文就来和大家聊聊这次的踩坑记录与解决方法,需要的可以参考一下2023-03-03Java如何优雅地避免空指针异常(NullPointerException)
这篇文章主要给大家介绍了关于Java如何优雅地避免空指针异常(NullPointerException)的相关资料,空指针异常(NullPointerException)是一种常见的运行时异常,它在Java编程中经常出现,需要的朋友可以参考下2024-03-03
最新评论