自定义Struts类型转换器不起作用 [英] Custom Struts type converter is not working
问题描述
我确实有一个Date
变量的getter/setter方法,如下所示:
I do have a getter/setter for the Date
variable, like so:
private Date registrationDate;
@TypeConversion(converter = "org.com.helper.DataHelper")
public Date getRegistrationDate() {
return registrationDate;
}
@TypeConversion(converter = "org.com.helper.DataHelper")
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
如您所见,我已经创建了一个自定义的struts
转换器,将传入的字符串转换为Date
格式,然后对其进行分配.但这似乎不起作用.这是DateHelper的代码:
As you can see I've created a custom struts
converter to convert the incoming string to the Date
format and then assign it. But it doesn't seem to work. Here is the code for DateHelper:
public class DateHelper extends StrutsTypeConverter {
private static final DateFormat FORMAT = new SimpleDateFormat("dd-MM-yyyy");
@Override
public Object convertFromString(Map arg0, String[] values, Class arg2) {
try {
System.out.println(values[0]+"called from datahelper");
return FORMAT.parse(values[0]);
} catch (Exception e) {
throw new TypeConversionException(e.getMessage());
}
}
@Override
public String convertToString(Map arg0, Object value) {
try {
return FORMAT.format(value);
} catch (Exception e) {
throw new TypeConversionException(e.getMessage());
}
}
}
我使用struts2-json
插件来获取和解析表单数据.该插件会自动分配所有字符串值,但是Date
确实有问题.
I use struts2-json
plugin to get and parse the form data. This plugin does assign automatically all string values but I do have an issue with the Date
.
这就是我从表单获取传递到Java的数据的方式.
This is how I get the data passed to Java from the form.
{"data":{"recordId":"123","registrationDate":"20-07-2016","hisId":"","herId":"","lastNameHe":"Asd","firstNameHe":"Asd","middleNameHe":"Asd","workPlaceHe":"","educationHe"}}
因此,根据我的理解,开始设置registrationDate
之前的代码应调用helper类,并将字符串转换为date
然后再调用registrationDate
setter ..但它似乎不起作用..我什至在助手代码中都放置了log
调用,但是它没有出现在eclipse中.
So, according to my understanding the code before starting to set the registrationDate
should call the helper class and convert the string to date
and then call the registrationDate
setter.. but it doesn't seem to work.. I've even put a log
call in the helper code but it doesn't show up in the eclipse.
推荐答案
好像struts2-json-plugin并不使用默认类型转换. :(
Seems like struts2-json-plugin doesn't use default type conversions. :(
要设置日期格式,可以使用具有format
属性的@JSON
批注.
For setting date format you can use @JSON
annotation which has format
property.
@JSON(format = "dd.MM.yyyy")
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
JSON插件文档-自定义序列化和反序列化
JSON plugin documentation - Customizing Serialization and Deserialization.
这篇关于自定义Struts类型转换器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!