Struts2类型转换器
Struts2类型转换器
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
public class Convert extends DefaultTypeConverter{
@Override
public Object convertValue(Map<String, Object> context, Object value,Class toType) {
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String[] dateInfo = (String[])value; //必须为字符串数组,这是Struts2考虑到了各种请求参数的各种情况
if(Date.class == toType){
try {
date = sdf.parse(dateInfo[0]);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
}
if(String.class == toType){
return sdf.format((Date)value);
}
return null;
} //用于struts2标签用于回显<s:field >这种
}
/**************************Action**************************/
package action;
import java.util.Date;
public class ConvertAction {
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String execute(){
System.out.println(date);
return "success";
}
}
//全局类型转换器xwork-conversion.properties(java.util.Date = util.Convert)(classpath目录下)
//局部类型转换器ConvertAction-conversion.properties(date = util.Convert)
(对应的Action包下)