我正在使用带有 Spring MVC 和 Hibernate 的 Web Flow 2.0.7。
我的问题是关于我的自定义类型的自定义转换器以及转换器内的数据库连接。
假设我有一个类型 Person,并且 Person 有一个自定义类型 Title 的字段,并且所有 Title 都已在我的数据库中。现在我有一个 html 表单,用户可以在其中填充 Person 实例,包括在选择下拉框中选择 Title。
在流程定义中,我从数据库获取所有标题,并使用自定义转换器将它们显示在下拉框中,将标题转换为字符串,然后再转换回标题。
我的问题是关于从String(这是数据库ID,我将其设置为元素上的值)转换回数据库中正确的Title对象的过程。基本上:如何做?
到目前为止,我无法将 titleManager 注入(inject)到我的转换器中以访问数据库。此场景已在 Spring Web Flow Forum 中评论过。 。另一种解决方案可能是在渲染 View 之前缓存标题,并在表单发布后以某种方式获取内存中的标题。
如果有人能启发我如何处理这种数据绑定(bind),我将非常感激。到目前为止我还无法让它工作,因此,我从其他很棒的网络流中得到的使用很少。
我已经发布了a thread on the Web Flow Board ,但仍然缺少最佳实践,我自己无法找到。
非常感谢!
沃尔夫拉姆
最佳答案
我曾经这样做过。 基本上我加载标题列表并将其放入我的表单模型中。在表单模型中,我还有一个 currentTitleId 或 selectedTitleId 变量来存储所选项目的值。该字段名称在 spring 组合框的“path”中设置,titleList 在“items”中设置。然后,在“itemValue”中设置要绑定(bind)的值,并在“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>
关于java - 如何在 Spring Web Flow 2 中编写自定义转换器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/783617/