【问题标题】:Spring Boot + Thymeleaf application - how to make several instances of the model attributeSpring Boot + Thymeleaf 应用 - 如何制作模型属性的几个实例
【发布时间】:2018-07-18 19:59:14
【问题描述】:

我有一个 Spring Boot + Thymeleaf 应用程序和以下工作代码:

控制器:

@Controller
@SessionAttributes( {"myBean"} )
public class MyController() {

    @ModelAttribute("myBean") 
    public MyBean getMyBean() {
        return new MyBean();
    }

    // multiple requests with "myBean"
    // ...

    @GetMapping("/page1")
    public String page1a(@ModelAttribute MyBean myBean) {
        // some code
        return "page";
    }

    @PostMapping("/page1")
    public String page1b(@ModelAttribute MyBean myBean) {
        // some code
        return "result";
    }
}

Thymeleaf 页面:

...
<form action="#" th:action="@{/page1}" th:object="${myBean}" method="post">
    <!-- some fields-->
</form>
...

当我一次只打开一页时,这很好用。不过,我想比较几个 result.html 页面上的结果,所以我需要能够同时处理多个页面。但我只有 1 个“myBean”实例,因此每次都会覆盖这些值。

是否可以有多个“myBean”实例?

【问题讨论】:

    标签: spring spring-boot thymeleaf modelattribute


    【解决方案1】:

    也许您可以通过在会话属性中定义另一个 bean 来解决这个问题,并在需要时将 myBean 映射到它:

    @Controller
    @SessionAttributes( {"myBean", "myResultBean"} )
    public class MyController() {
    
        @ModelAttribute("myBean") 
        public MyBean getMyBean() {
            return new MyBean();
        }
    
        // multiple requests with "myBean"
        // ...
    
        @GetMapping("/page1")
        public String page1a(@ModelAttribute MyBean myBean) {
            // some code
            return "page";
        }
    
        @PostMapping("/page1")
        public String page1b(@ModelAttribute MyBean myBean, @ModelAttribute("myResultBean") MyBean myResultBean) {
            // map myBean to myResultBean.
           // some code
    
            return "result";
        }
    }
    

    【讨论】:

    • 感谢您回答我的问题。你的建议很好,但我认为它不适用于我的情况。我在结果页面之前有多个请求,如果我没有达到结果但同时开始一个新页面,我会丢失“myBean”中的当前数据。
    猜你喜欢
    • 2016-07-12
    • 2018-12-16
    • 2017-07-30
    • 2022-01-22
    • 2016-11-29
    • 2016-08-01
    • 1970-01-01
    • 2016-01-26
    • 2017-10-01
    相关资源
    最近更新 更多