Java – How to write a custom converter in Spring Web Flow 2


I am using Web Flow 2.0.7 with Spring MVC and Hibernate.

My problem is about custom converters for my custom types and database connection from within my converter.

Let's say I have a type Person and the Person has a field of my custom type Title, and all Titles are already in my database. Now I have an html form, in which a user can populate a Person instance, including selecting the Title in a select drop-down box.

In the flow definition I get all Titles from the database and they are shown in the dropdown box using a custom converter, converting Title to String and later back to Title.

My question is about the process of converting back from String (which is the database ID, which I set as value on the element) to the correct Title object from my database. Basically: How to do it?

So far, I was unable to get a titleManager injected into my converter to get access to the database. This scenario was commented on in the Spring Web Flow Forum. Another solution might be to cache the Titles before rendering the view and somehow get the in-memory Title after the form was POSTed.

I would really appreciate it, if someone could enlighten me, how to handle this kind of data binding. I was unable to get it working so far and thus, I get minimal use out of the otherwise awesome webflows.

I already posted a thread on the Web Flow Board, but still missing a best-pratice, which I am unable to find by myself.

Thank you so much!


Best Solution

I use to do this. Basically I load the list of Titles and put it in my form model. In the form model I have also a currentTitleId or selectedTitleId variable to store the value of the selected item. This field name is set in the "path" of the spring combobox and the titleList is set in the "items". Then the value that you want to bind is set in the "itemValue" and the text to be shown for that value in "itemLabel". That's it.

In my form model:

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

List titleList = getTitlesFromMyDatabaseHereOrSomewhereElse();

In my jsp:

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

I assume that your Title class will be something like this:

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

You can also customize you combobox a little more like this:

    <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>
Related Question