Reputation: 1
Struts2 inserts java.lang.Strings
into Maps as default, but... is there a way to override that behavior for some parameters and insert different Objects using many custom Type Converters?
For example, in a Java class we can declare a HashMap and put something like:
myHashMap.put(“name”,”myName”); //this is a String
myHashMap.put(“id”,new Integer(“101”)); //this is an Integer
myHashMap.put(“date”,java.util.Calendar.getInstance().getTime()); //this is a Date
Is it possible to assign the correct java.lang.Object
directly from the <s:form>
using Type Converters?
If you have something like this in your <s:form>
:
<s:textfield name="myHashMap['name']"/>
<s:textfield name="myHashMap['id']"/>
<s:textfield name="myHashMap['date']"/>
Every value ends as a java.lang.String
inside the HashMap, instead of having a String, an Integer an a Date...
I tried to create my own Type Converter with no luck... I guess Struts2 wants a POJO with setters and getters for each parameter, but the HashMap uses the “put(Key,Value)
” method.
I have the setters and getters for “myHashMap”, but I thought Struts would somehow use it like a POJO when setting the parameters (when calling “put(Key,Value)
”).
I created “MyAction-conversion.properties” file and wrote this:
date=app.converter.MyDateConverter
It didn't work... Then I tried also doing this:
myHashMap['date']=app.converter.MyDateConverter # (didn't work)
myHashMap.date=app.converter.MyDateConverter # (didn't work)
The converter isn't called at all! I do have “MyDateConverter” class and it is working fine. If I use a POJO (instead of the HashMap) and create the setters and getters inside the POJO for “name”, “id” and “date” it works great. But the thing is that I want to use something more generic, like a HashMap, in order to change the name of the parameters in the form or add more without having to create another POJO.
For the moment, it works using the HashMap if you expect to receive only Strings, but I don't know how to call a Type Converter to receive custom Objects. The converter isn't called and I end always with Strings.
Upvotes: 0
Views: 328
Reputation: 11
struts2 can convert java.util.Date from String without coding your converter. Infact,'date' is String type ,struts can not find it by it's content but type.
Upvotes: 1
Reputation: 11055
Doubtful, and if you can, don't. Doing so would require the use of a raw map and casting to retrieve the values. Type safety is your friend.
But the thing is that I want to use something more generic, like a HashMap, in order to change the name of the parameters in the form or add more without having to create another POJO.
That isn't a better design. Stick with the POJO approach.
Upvotes: 0