【问题标题】:Can I have Multiple @ModelAttribute annotations in single Spring Handler Method我可以在单个 Spring Handler 方法中有多个 @ModelAttribute 注释吗
【发布时间】:2018-12-12 05:29:47
【问题描述】:

问题陈述:我必须在 JSP 上显示来自两个独立模型的数据。

比如说有两种模型:account和Student。

Student Model 的属性是可编辑的,所以我可以在 spring 表单中使用 modelattribute 并将数据从 jsp 映射到我的 java 对象。

account 的属性是只读的,但是我已经在 modelattribute 中提到了 student 模型,在 jsp 表单中,每个 jsp 表单只能有一个 modelattribute,所以我不能将 account 分配给 Jsp spring 表单中的 modelattribute .在这种情况下,帐户模型的数据将如何在 Jsp 中显示。

其次,写作: public String requestHandlingMethod(@ModelAttribute Student student, @ModelAttribute Student student)

这是否有效,即在 Spring 处理程序方法中有两个 @ModelAttribute

【问题讨论】:

    标签: java spring jsp


    【解决方案1】:

    一种方法是创建一个具有 Student 和 Account 作为属性的新类。这样,您的处理程序方法中只需要一个 @ModelAttribute。

    Public Class StudentAcctWrapper{
    private Student student;
    private Account account;
    

    可以通过 StudentAcctWrapper 实例在您的视图中访问相应的字段。

    【讨论】:

    • 感谢@Dev 的回复,但我不希望这两个模型成为另一个类的一部分。有没有其他方法可以解决这个问题?
    猜你喜欢
    • 2018-01-10
    • 2012-12-02
    • 2011-04-12
    • 1970-01-01
    • 2013-06-04
    • 2018-05-11
    • 1970-01-01
    • 2017-08-16
    相关资源
    最近更新 更多