经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
SpringMVC 重定向参数RedirectAttributes实例
来源:jb51  时间:2021/12/17 11:53:08  对本文有异议

重定向参数RedirectAttributes

SpringMVC 中常用到 redirect 来实现重定向。但使用场景各有需求,如果只是简单的页面跳转显然无法满足所有要求,比如重定向时需要在 url 中拼接参数,或者返回的页面需要传递 Model。

SpringMVC 用 RedirectAttributes 解决了这两个需要。

1. addAttribute

  1. @RequestMapping("/save")
  2. public String save(User user, RedirectAttributes redirectAttributes) {
  3. redirectAttributes.addAttribute("param", "value1");
  4. return "redirect:/index";
  5. }

请求 /save 后,跳转至/index,并且会在url拼接 ?param=value1。

2. addFlashAttribute

  1. @RequestMapping("/save")
  2. public String save(User user, RedirectAttributes redirectAttributes) {
  3. redirectAttributes.addFlashAttribute("param", "value1");
  4. return "redirect:/index";
  5. }

请求 /save 后,跳转至 /index,并且可以在 index 对应的模版中通过表达式,比如 jsp 中 jstl 用 ${param},获取返回值。该值其实是保存在 session 中的,并且会在下次重定向请求时删除。

RedirectAttributes 中两个方法的简单介绍就是这样。

重定向携带参数问题

问题描述

A.jsp发送请求进入Controller,并想重定向到B.jsp并携带参数,发现携带的参数前台获取不到,然后采用以下方法即可

  1. @RequestMapping("/index")
  2. public String delete(String id, RedirectAttributes redirectAttributes) {
  3. redirectAttributes.addFlashAttribute("msg","删除成功!");
  4. return "redirect:hello";
  5. }
  1. @RequestMapping("hello")
  2. public String index( @ModelAttribute("msg") String msg) {
  3. return "sentinel";
  4. }

首先进入delete方法,将msg放在redirectAttributes里,然后重定向到hello,通过@ModelAttribute(“msg”) String msg获取到msg的值,那么自然sentinel页面就能获取到msg的值。

问题来源

B.jsp发送请求,跳转到A.jsp,并将请求所产生的数据携带到A页面。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号