Spirng MVC 重定向传递对象

在 Spring MVC 中我们会经常遇到重定向。

@RequestMapping("/order/saveorder.html")
public String saveOrder(Order order) {
Long orderId = service.addOrder(order);
return "redirect:/order/detail.html?orderId=" + orderId;
}

但是我们会发现,URL重定向过程中,并不能有效的传递对象,因为HTTP的重定向参数是以字符串传递的。这个时候 Spring MVC 提供了一个方法,flash 属性。你需要提供的数据模型就是一个 RedirectAttribute

    @GetMapping("/")
    public String index(RedirectAttributes ra,Role role) {
        roleService.insertRole(role);
        ra.addFlashAttribute("role",role);
        return "redirect:./test.html";
    }

这样就能传递 POJO 对象给下一个地址了,那么它是如何做到传递 POJO?使用 ra.addFlashAttribute 方法后, Spring MVC 会将数据保存到 Session 中,重定向之后会将其清除,这样就能够传递数据给下一个地址了。

原文地址:https://www.cnblogs.com/dowhile/p/Spirng-MVC-zhong-ding-xiang-chuan-di-dui-xiang.html