struts2视频学习笔记 13-14(自定义局部和全局类型转换器(转换Date格式))

struts2视频学习笔记 13-14(自定义局部和全局类型转换器(转换Date格式)) 课时13

  • 自定义类型转换器

    局部(对某个action类)

 package tutorial;

 import java.util.Date;

 public class HelloWorld  {
private Date birthday; public Date getBirthday() {
return birthday;
} public void setBirthday(Date birthday) {
System.out.println(birthday);
this.birthday = birthday;
} public String execute(){
return "success";
} public String add(){
return "success";
}
}
 package type;

 import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map; import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter; public class DateTypeConverter extends DefaultTypeConverter { @Override
public Object convertValue(Map<String, Object> context, Object value,
Class toType) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
try {
if(toType == Date.class) { //字符串转Date类型
String[] param = (String[]) value;
return dateFormat.parse(param[0]);
} else if (toType == String.class) { //Date转字符串
Date date = (Date) value;
return dateFormat.format(date);
}
}catch (java.text.ParseException e) { } return null;
} }

    将上面的类型转换器注册为局部类型转换器:
在Action类所在的包下放置ActionClassName-conversion.properties文件,ActionClassName是Action的类名,后面的-conversion.properties是固定写法,对于本例而言,文件的名称应为HelloWorldAction-conversion.properties 。在properties文件中的内容为:
    属性名称=类型转换器的全类名(birthday=type.DateTypeConverter)

struts2视频学习笔记 13-14(自定义局部和全局类型转换器(转换Date格式))   struts2视频学习笔记 13-14(自定义局部和全局类型转换器(转换Date格式))

struts2视频学习笔记 13-14(自定义局部和全局类型转换器(转换Date格式)) 课时14

  • 自定义全局类型转换器(对整个应用)

将上面的类型转换器注册为全局类型转换器:
        在WEB-INF/classes下放置xwork-conversion.properties文件 。在properties文件中的内容为:待转换的类型=类型转换器的全类名
        对于本例而言, xwork-conversion.properties文件中的内容为:
        java.util.Date=type.DateTypeConverter

上一篇:tushare模块的应用


下一篇:[转]Spring MVC之@RequestMapping 详解