为struts2自定义类型转换器:Date的转换
struts2的类型转换器分为局部和全局,局部就是只为某一个Action服务,而全局则是为所有的Action服务。
局部类型转换器的实现:
第一步:新建一个从DefaulTypeConvertion继承的类
package blog.typeConvertion; import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Map; import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter; public class DateTyepConverter extends DefaultTypeConverter { @Override public Object convertValue(Map context, Object value, Class toType) { //value是字符串数组形式的,为的是能兼容所有的数据类型,如多个checkbox的数据为数组 //通过request.getParameterValues()得到 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); try { if (toType == Date.class) {//字符串转换成Date String[] date = (String[])value; return dateFormat.parse(date[0]); }else if (toType == String.class) {//Date转化成string Date birthday = (Date)value; return dateFormat.format(birthday); } } catch (ParseException e) { e.printStackTrace(); } return null; } }注意:转换的实现必须是双向的,另外一个转换是struts2在反向显示的时候用的。
第二步:在某个包下新建一个ActionClassName-convertion.properties的文件,内容为
比如为类blog.action.HelloWorld服务的,则文件名称为
HelloWorld-conversion.properties
内容为:
birthday=blog.typeConvertion.DateTyepConverter
全局类型转换器的实现:
与局部类型转换器的实现的区别只在于properties文件的区别:
全局类型转换的properties文件的文件名应命名为xwork-conversion.properties
并且内容为:
java.util.Date=blog.typeConvertion.DateTyepConverter存放位置应为src目录下。