众所周知,java有八大基本的类型,struts2能对这八大基本类型以及String、Date等常用类型提供自动转换。
但是,仅仅这些远远不能满足我们的需要。
原因:因为页面中的类型都是属于字符串类型的,而java是一种强类型语言,这时候我们需要把输入的字符串转型成为相应的类型。
在类型转换器的定义中也分为两种:
局部类型转换器:对某个action转换类型起作用。
全局类型转换器:对所有action转换类型起作用。
这里用一个日期来举例子:
比如我们在页面输入20140828,如果Action类的属性是Date类型的,则它不能够正确接收到这个时间值。
如果我们输入2014-08-28,则Action类的Date类型的属性就可以正确接收到这个时间值。
所以,这个时候我们就需要用到类型转换了。
首先我们需要定义一个简单的Action类继承ActionSupport类:
package cn.action;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport{
private Date birthday;
public Date getBirthday() {
System.out.println("get:"+birthday);
return birthday;
}
public void setBirthday(Date birthday) {
System.out.println("set:"+birthday);
this.birthday = birthday;
}
public String excute(){
return SUCCESS;
}
}
package cn.type.Converter;
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 DateTypeConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map arg0, Object value,Class toType) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
try {
if (toType == Date.class) {// 当字符串向Date类型转换时
String[] params = (String[]) value;// Request.getParameterValues()
System.out.println("value="+value);
System.out.println("时间:"+dateFormat.parse(params[0]));
return dateFormat.parse(params[0]);
} else if (toType == String.class) {// 当Date转换成字符串时
System.out.println(value);
Date date = (Date) value;
return dateFormat.format(date);
}
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return null;
}
}
在需要生效的Action类的包下新建ActionName-conversion.properties该文件,其中 ActionName是需要转换生效的Action的类名,后面的-conversion固定。
我们这里需要建立的是:HelloWorldAction-conversion.properties
birthday=cn.type.Converter.DateTypeConverter
这是项目的工程目录:
三、全局类型转换器:
局部类型转换器仅仅对指定的Action的指定属性进行转换。
全局类型转换器对所有Action的特定类型进行转换。
在src目录下新建xwork-conversion.properties,该文件的内容是待转换的类=转换器的名字,即com.shengsiyuan.bean.User=com.shengsiyuan.converter.UserConverter2
原文地址:http://blog.csdn.net/u010800530/article/details/38905083