在Struts中我们经常要处理用户录入的日期字符串,将其转换为java.util.Date类型。在这里我们提供两种方式来实现这样的转换。
1 在ActionForm子类中,创建两个变量来处理日期,一个为Date类型,一个为String类型(临时变量),我们使用String类型的变量来接受用户的录入,再编码将其转换为Date类型,在页面输出时,在根据Date类型生成自定义的文本格式。这种方式灵活性大,不过需要你多付出点劳动。
2 编写一个plugin实现自动转换。Struts下各种对象类型的转换是通过BeanUtils的Converter实现,所以我们只需向 BeanUtils注册一个日期字符转换的Converter即可,这种方式不需要你编写代码进行转换,不过在页面呈现的时候,你可能需要进行格式化,从 Date对象之间生产的字符串(toString())往往不是你需要的,使用JSTL就可以的。
首先编写一个日期转换的Converter类:
public class DateConverter implements Converter {
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public Object convert(Class arg0, Object value) {
try {
return sdf.parse((String) value);
} catch (Exception e) {
ex.printStackTrace();
}
}
}
然后编写一个Struts的plugin,执行Converter注册:
public class ConvertPlugIn implements PlugIn {
public void destroy() {
ConvertUtils.deregister();
}
public void init(ActionServlet arg0, ModuleConfig arg1)
throws ServletException {
ConvertUtils.register(new DateConverter(), Date.class);
}
}
最后在struts-config.xml进行plugin声明:
<plug-in className="DateConverter" />
进行日期转换,这对Struts来说是非常有益的。Struts的ActionForm一直被认为是设计的缺陷,但是通过BeanUtils可以快速实现 ActionForm、VO、PO对象之间的转换,这就要求ActionForm设计比较合理,当然在ActionForm中实现从采集字符串到日期的转换会节省很多时间,我们只需关注域对象间的转换就可以啦。
当然在struts2我们进行如下转换:
这儿拷贝的网上的,原文地址:http://www.blogjava.net/max/archive/2006/11/07/79602.html
Date的转换类似,在源代码文件夹的tutorial包中新建LocaleConverter.java文件,代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
public class LocaleConverter extends ognl.DefaultTypeConverter {
@Override
public Object convertValue(Map context, Object value, Class toType) {
if (toType == Locale. class ) {
String locale = ((String[]) value)[ 0 ];
return new Locale(locale.substring( 0 , 2 ), locale.substring( 3 ));
} else if (toType == String. class ) {
Locale locale = (Locale) value;
return locale.toString();
}
return null ;
}
}
再接下来,在源代码文件夹下新建xwork-conversion.properties,并在其中添加如下代码: