Struts2的类型转换是基于OGNL表达式的,由于请求的参数都是字符串,而JAVA 本身属于强类型的的语言,这样就需要把字符串转换成其他类型。主要通过以下2步完成:
1.首先通过实现TypeCoverter接口或者继承DefaultTypeConverter实现类(该类实现了TypeCoverter接口)来实现自己的类型转换器(重写convertValue方法即可)
(1) TypeCoverter接口:
public interfaceTypeConberter{
public Object convertValue(Map context,Object target,Member member,String propertyName,Object value, Class toType)
{}
}
由于TypeCoverter接口太复杂,所以OGNL 项目还提供了一个实现该接口的类 :DefaultTypeConverter.
(2) DefaultTypeConverter接口:
public class UserTypeConvert extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> context, Object value, Class toType) {
return null;
}
}
其中,context是类型转换环境的上下文,value是需要转换的参数,toType 是转换后的目标类型。
eg:日期格式转换
LoginAction.java:
public class LoginAction {
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String execute() throws UnsupportedEncodingException{
return "success";
}
}
DateTypeConvert.java:
public class UserTypeConvert extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> context, Object value, Class toType)
{
SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
try{
if(toType == Date.class) {
String [] datevalue = (String [])value;
return dateformat.parse(datevalue[0]);
} else if(toType == String.class) {
Date datevalue = (Date)value;
return dateformat.format(datevalue);
}
}catch (ParseException e){
e.printStackTrace();
}
return null;
}
}
2.将该转换器注册在WEB应用中,这样 Struts 2 框架才能使用该类型的转换器。
类型转换器的注册有 3种:
(1)注册局部类型转换器:仅仅对某个Action的属性起作用。
(2)注册全局类型的转换器:对所有Action 都有效。
(3)使用 JDK1.5 的注释来注册转换器。
局部类型转换器:
在需要生效的Action类的包下放置ActionName-conversion.properties,其中 ActionName是需要转换生效的Action的类名,后面的-conversion固定。
内容: 待转换的类型=类型转换器的全类名。 注意:类型转换器是需要加包名,而且最后不能加标点符号
LoginAction-conversion.properties:
birthday =convert.UserTypeConvert
全局类型转换器:
在WEB-INF/class下放置xwork-conversion.properties文件。文件名是固定的。
内容:待转换的类型 = 类型转换器的全类名
xwork-conversion.properties:
java.util.Date = convert.UserTypeConvert