java - 使用 RedirectAttributes.addFlashAttribute 时刷新后将对象保留在 View 中

标签 java spring jakarta-ee spring-mvc

感谢 Spring 3.1,我可以使用 RedirectAttributes.addFlashAttribute 实现 Post/Redirect/Get,但似乎有一个小问题

这是持久化表单对象的方法,然后重定向到 View 以显示该表单对象:

@RequestMapping(value = "/{formType}/onTheEarch", method = RequestMethod.POST)
public String submitAndRedirect(SomeWebForm someWebForm,
        @PathVariable("formType") String formType,
        final RedirectAttributes redirectAttributes) {

            // do something according to formType
            // .......

            redirectAttributes.addFlashAttribute("webObject", webObject);
            String view = "redirect:/formType/toTheMoon";
    }

这是将用户引导到显示表单对象的 View 的方法

@RequestMapping(value = "/{formType}/toTheMoon", method = RequestMethod.GET)
public String submitAndRedirect(@PathVariable("formType") String formType) {
            // do something according to formType
            // .......
            String view = "toTheMoon";
    }

到目前为止一切都很好,但还有一个不足。当我刷新 View toTheMoon 时,一切都消失了。所以这里的问题是

(1)How does `RedirectAttributes.addFlashAttribute` works? 
(2)How can I keep the object from "FlashAttribute" even after refreshing the page?

我知道对于第二个问题,我们可以避免 RedirectAttributes.addFlashAttribute 并仅传入 URL 中的任何参数来实现 RGP 模式,但是,我尝试避免这种情况,因为参数值很敏感,不应在浏览器上向用户公开。那么该怎么办呢?

最佳答案

spring documentation chapter 17.6 中所述

Flash attributes are saved temporarily before the redirect (typically in the session) to be made available to the request after the redirect and removed immediately.

如果您希望结果在更多请求中持续存在,您可以将它们存储在带有某些标识符的 session 中,并仅将标识符作为请求参数传递到结果页面

我通常采用的其他方法是检查结果模型是否存在于结果页面上,如果不存在,则直接重定向到错误页面(即:用户不打算按刷新/直接访问结果页面,如果他们只是呈现错误) )。然后使用 javascript 进行客户端刷新预防

关于java - 使用 RedirectAttributes.addFlashAttribute 时刷新后将对象保留在 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16179973/

相关文章:

java - 从 MySQL 数据库验证散列密码

Java 7 无法从对象检索信息

java:检查带有特殊字符的字符串,少数除外

java - 从 DAO 返回时的 Spring/JPA 分离实体

javascript - 从 xsd 获取 html 表单

java - 切换仅在第一次有效

java - 使用 Mockito 模拟 HttpSession

jakarta-ee - Glassfish 与 Glassfish-网络配置文件

jakarta-ee - 多少 EJB 太多了?

java - jsp 文件中的 JSON 只接受来 self 的 MVC Controller 的 null 返回值。