SpringBoot中RedirectAttributes重定向传递对象解决办法

本文介绍了在SpringBoot中,当使用重定向(redirect)时如何传递参数。对于字符串,可以利用RedirectAttributes的addFlashAttribute方法。而对于自定义对象,需要通过RequestContextUtils获取InputFlashMap,然后将对象放入Model中。示例代码展示了从Controller1到Controller2的重定向过程中,如何成功传递并接收字符串和自定义User对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot两个Controller重定向传参解决办法

​ 这是我昨天遇到的一个问题,Controller中想要传递参数时,比较常用的是Model,但是如果Controller返回采用重定向的方法,model中的数据则不能成功带到重定向的页面中去。

​ 在网上查阅一些资料后,发现可以用RedirectAttributes。具体代码如下:

Controller1

@RequestMapping("/testA")
    public String A(RedirectAttributes redirectAttributes){
        redirectAttributes.addFlashAttribute("msg","这是redirectAttributes的addFlashAttribute方法");
        return "redirect:/testB";
    }

Controller2

@RequestMapping("/testB")
   public String B(){
        return "test";//返回test.html页面
   }

​ 前端接收页面,这里我使用的是thymeleaf模板。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<span th:text="${msg}"></span>

</body>
</html>

​ 非常简单的例子,成功接收到了,重定向传递的数据。

在这里插入图片描述

​ 但是!我尝试了很多次发现有上面这种方法可以传递String类型的数据,但是如果传递的是一个自定义对象的话,这种方法就不能成功传递数据了。就需要以下这么操作。

Controller1

@RequestMapping("/testA")
    public String A(RedirectAttributes redirectAttributes){
        redirectAttributes.addFlashAttribute("msg","这是redirectAttributes的addFlashAttribute方法传递对象");
        User user = new User();
        user.setName("吴彦祖");
        redirectAttributes.addFlashAttribute("user", user);
        return "redirect:/testB";
    }

这里User是我自定义的一个类,并把它的name属性赋值为“吴彦祖”。

Controller2

@RequestMapping("/testB")
    public String B(Model model, HttpServletRequest request){
        Map<String,Object> map=((Map<String, Object>) RequestContextUtils.getInputFlashMap(request));
        User user=(User) map.get("user");
        model.addAttribute("user",user);
        return "test";
    }

这样便能将user对象传递给前端页面。前端页面代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<span th:text="${msg}"></span><br>
<span th:text="${user?.getName()}"></span>

</body>
</html>

user?.getName()的意思为如果user不为空,则取name值。

运行结果如下:

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我不读研

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值