温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringMVC 重定向参数RedirectAttributes的示例分析

发布时间:2021-12-17 12:30:05 来源:亿速云 阅读:119 作者:小新 栏目:开发技术

这篇文章主要介绍SpringMVC 重定向参数RedirectAttributes的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

重定向参数RedirectAttributes

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

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

1. addAttribute

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

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

2. addFlashAttribute

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

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

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

重定向携带参数问题

问题描述

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

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

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

问题来源

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

以上是“SpringMVC 重定向参数RedirectAttributes的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI