• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
zziy的java笔记
博客园    首页    新随笔    联系   管理    订阅  订阅
struts2视频学习笔记 13-14(自定义局部和全局类型转换器(转换Date格式))

课时13

  • 自定义类型转换器

    局部(对某个action类)

 1 package tutorial;
 2 
 3 import java.util.Date;
 4 
 5 public class HelloWorld  {
 6     private Date birthday;
 7 
 8     public Date getBirthday() {
 9         return birthday;
10     }
11 
12     public void setBirthday(Date birthday) {
13         System.out.println(birthday);
14         this.birthday = birthday;
15     }
16 
17     public String execute(){
18         return "success";
19     }
20     
21     public String add(){
22         return "success";
23     }
24 }

 

 1 package type;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 import java.util.Map;
 6 
 7 
 8 import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
 9 
10 public class DateTypeConverter extends DefaultTypeConverter {
11 
12     @Override
13     public Object convertValue(Map<String, Object> context, Object value,
14             Class toType) {
15         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
16         try {
17             if(toType == Date.class) { //字符串转Date类型
18                 String[] param = (String[]) value;
19                 return dateFormat.parse(param[0]);
20             } else if (toType == String.class) { //Date转字符串
21                 Date date = (Date) value;
22                 return dateFormat.format(date);
23             }
24         }catch (java.text.ParseException e) {    }
25         
26         return null;
27     }
28 
29 }

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

  

  课时14

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

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

 

posted on 2015-10-19 01:40  zziy  阅读(277)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3