【问题标题】:How do I write a custom converter in Spring Web Flow 2?如何在 Spring Web Flow 2 中编写自定义转换器?
【发布时间】:2010-10-21 11:34:15
【问题描述】:

我正在使用带有 Spring MVC 和 Hibernate 的 Web Flow 2.0.7。

我的问题是关于我的自定义类型的自定义转换器和我的转换器中的数据库连接。

假设我有一个类型 Person 并且 Person 有一个我的自定义类型 Title 的字段,以及所有 Titles 已经在我的数据库中。现在我有一个 html 表单,用户可以在其中填充一个 Person 实例,包括在选择下拉框中选择 Title

在流程定义中,我从数据库中获取所有 Titles,它们使用自定义转换器显示在下拉框中,将 Title 转换为 String em> 然后返回到标题

我的问题是关于从 String(这是数据库 ID,我在元素上设置为值)转换回正确的 Title 对象的过程我的数据库。基本上:怎么做?

到目前为止,我无法将 titleManager 注入到我的转换器中以访问数据库。这个场景在Spring Web Flow Forum 中有评论。另一种解决方案可能是在呈现视图之前缓存 Titles,并在表单发布后以某种方式获取内存中的 Title

如果有人能告诉我如何处理这种数据绑定,我将不胜感激。到目前为止,我无法让它工作,因此,我从原本很棒的 webflow 中得到了很少的使用。

我已经发布了a thread on the Web Flow Board,但仍然缺少最佳实践,我自己无法找到。

非常感谢!

沃尔夫拉姆

【问题讨论】:

    标签: java spring-mvc converter spring-webflow


    【解决方案1】:

    我曾经这样做过。 基本上我加载标题列表并将其放入我的表单模型中。在表单模型中,我还有一个 currentTitleId 或 selectedTitleId 变量来存储所选项目的值。此字段名称设置在 spring 组合框的“路径”中,而 titleList 设置在“项目”中。然后在“itemValue”中设置您要绑定的值,并在“itemLabel”中为该值显示文本。就是这样。

    在我的表单模型中:

    private int currentTitleId;
    public long getCurrentTitleId() { return this.currentTitleId; }
    public void setCurrentTitleId(long currentTitleId) { this.currentTitleId = currentTitleId; }
    
    List titleList = getTitlesFromMyDatabaseHereOrSomewhereElse();
    

    在我的jsp中:

    <form:label path="currentTitleId">Title</form:label>
    <form:select path="currentTitleId" items="${formModel.titleList}" itemLabel="titleDescription" itemValue="titleId" />
    

    我假设你的 Title 类是这样的:

    class Title {
        public long getTitleId() { return this.titleId; }
        public long getTitleDescription() { return this.titleDescription; }
    }
    

    您还可以像这样自定义组合框:

        <form:select path="currentPhoneNumberId">
        <form:option value="">-</form:option>
        <c:forEach items="${formModel.phoneList}" var="phone">
            <form:option value="${phone.phoneNumberId}">${phone.phoneNumberId} - ${phone.description}</form:option>
        </c:forEach>
    </form:select>
    

    【讨论】:

    • 天啊,非常感谢您提供这个示例!在过去的两天里,我一直在努力解决这个问题。
    【解决方案2】:

    我不太确定 Spring Web Flow,但是使用普通的 Spring MVC 注册一个新的 PropertyEditor 就足够了,然后这些东西会自动工作

    http://static.springframework.org/spring/docs/2.5.x/reference/validation.html#beans-beans-conversion-customeditor-registration

    http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann-webdatabinder

    所以我会创建一个新的 PropertyEditor,它获取一个服务或 dao,它负责从数据库中获取数据,并且在 PropertyEditor 中,您可以将 id 转换为您的键类型并从数据库中获取值并返回它。我只是没有合适的例子,但我希望你能明白要点。

    【讨论】:

    • 感谢您的回答。不幸的是,我的问题正是 MVC 和 Web Flow 中的转换器之间的明显差异。我确实有属性编辑器在工作,但在 Web Flow 中没有这样做。
    猜你喜欢
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 2011-05-13
    • 2021-03-25
    • 2016-03-18
    相关资源
    最近更新 更多