webwork自定义日期类型转换

[ webwork2.2.6]

webwork提供了很多常用的类型转换,但有时还是有特殊的情况,需要添加自己的类型转换器,增强系统易用性.
如这里的例子是将 "20080808" 这种用户输入的日期直接转换成 java 日期类型.虽然现在网页设计上都会提供一个日期选择器,但是键盘输入总是快速输入的首选,而没有分隔符的日期,击键的次数最少,而这个格式,是默认类型转换器所无法识别的.

自定义的类型转换器可以从 com.opensymphony.webwork.util.WebWorkTypeConverter 继承,也可双 ognl.DefaultTypeConverter 继承.
使用自定义类型转换器有两种方式,一种是全局设置,对于整个应用起作用,另外是类设置,只针对某特定类.
全局设置的配置文件名为:xwork-conversion.properties,路径为classes目录;
类设置的配置文件名为:<类名>-conversion.properties,路径为对应的包目录.

日期转换器的目的是将用户输入的yyyyMMdd格式的字符串,转换成数据库可用的java.sql.Date
package  com.lingsmm.common.utils;

import  java.sql.Date;
import  java.text.SimpleDateFormat;
import  java.util.Map;

import  com.opensymphony.webwork.util.WebWorkTypeConverter;
import  com.opensymphony.xwork.util.TypeConversionException;

public   class  DateConverter  extends  WebWorkTypeConverter  {

    @SuppressWarnings(
"unchecked")
    @Override
    
public Object convertFromString(Map context, String[] values, Class toClass) {
        
try{
            SimpleDateFormat sdft 
= new SimpleDateFormat("yyyyMMdd");
            
long times = sdft.parse(values[0].toString()).getTime();
            
return new Date(times);
        }
catch(Exception e){
            
throw new TypeConversionException();
        }

    }


    @SuppressWarnings(
"unchecked")
    @Override
    
public String convertToString(Map context, Object o) {
        SimpleDateFormat sdft 
= new SimpleDateFormat("yyyy年MM月dd日");
        Date date 
= (Date)o;
        
return sdft.format(date);
    }

}

这个类实现了两个方法,convertFromString() 和 convertToString(),方法作用与内容比较一目了然.
在输出字符串时,这里直接写死了格式字符,如果要考虑多语种版本,可以根据客户端的语言类别,创建对应的系统格式化类来输出.

另外是异常,如果类型转换失败,应当抛出 XWorkException 或 TypeConversionException,建议使用后者,比较明确地指出是类型转换错误.(在异常处理时,由于没看文档,我直接抛出 Exception,结果无法通过编译,因为接口定义是不抛出异常的,子类实现方法只能抛出比它更小范围的异常或不抛出异常,但不能抛出比它更大范围的异常; 这里的两个异常类是 RuntimeException,编译器是不作检查的.)
xwork 在执行 ParametersInterceptor 时,会处理异常,并输出字段的错误信息.

我们再来看一下 WebWorkTypeConverter, 他继承自 DefaultTypeConverter
/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 
*/

package  com.opensymphony.webwork.util;

import  ognl.DefaultTypeConverter;

import  java.util.Map;

/**
 * <!-- START SNIPPET: javadoc -->
 *
 * Base class for type converters used in WebWork. This class provides two abstract methods that are used to convert
 * both to and from strings -- the critical functionality that is core to WebWork's type coversion system.
 *
 * <p/> Type converters do not have to use this class. It is merely a helper base class, although it is recommended that
 * you use this class as it provides the common type conversion contract required for all web-based type conversion.
 *
 * <p/> There's a hook (fall back method) called <code>performFallbackConversion</code> of which 
 * could be used to perform some fallback conversion if <code>convertValue</code> method of this 
 * failed. By default it just ask its super class (Ognl's DefaultTypeConverter) to do the conversion.
 * 
 * <p/> To allow WebWork to recongnize that a converison error has occurred, throw an XWorkException or 
 * preferable a TypeConversionException.
 *
 * <!-- END SNIPPET: javadoc -->
 * 
 * 
@version $Date: 2006-09-08 20:36:19 +0200 (Fri, 08 Sep 2006) $ $Id: WebWorkTypeConverter.java 2720 2006-09-08 18:36:19Z tmjee $
 * 
 
*/

public   abstract   class  WebWorkTypeConverter  extends  DefaultTypeConverter  {
    
public Object convertValue(Map context, Object o, Class toClass) {
        
if (toClass.equals(String.class)) {
            
return convertToString(context, o);
        }
 else if (o instanceof String[]) {
            
return convertFromString(context, (String[]) o, toClass);
        }
 else if (o instanceof String) {
            
return convertFromString(context, new String[]{(String) o}, toClass);
        }
 else {
            
return performFallbackConversion(context, o, toClass);
        }

    }

    
    
/**
     * Hook to perform a fallback conversion if every default options failed. By default
     * this will ask Ognl's DefaultTypeConverter (of which this class extends) to 
     * perform the conversion.
     * 
     * 
@param context
     * 
@param o
     * 
@param toClass
     * 
@return The fallback conversion
     
*/

    
protected Object performFallbackConversion(Map context, Object o, Class toClass) {
        
return super.convertValue(context, o, toClass);
    }

    

    
/**
     * Converts one or more String values to the specified class.
     *
     * 
@param context the action context
     * 
@param values  the String values to be converted, such as those submitted from an HTML form
     * 
@param toClass the class to convert to
     * 
@return the converted object
     
*/

    
public abstract Object convertFromString(Map context, String[] values, Class toClass);

    
/**
     * Converts the specified object to a String.
     *
     * 
@param context the action context
     * 
@param o       the object to be converted
     * 
@return the converted String
     
*/

    
public abstract String convertToString(Map context, Object o);
}


这个类封装了 convertValue() 方法,并将它拆分成三个抽象方法,从这里我们可以清楚的看出,进行 FromString 转换里,传入的对象是一个字符串数组.如果直接从 DefaultTypeConverter 类继承的话,很容易想当然的以为是一个字符串对象.
performFallbackConversion() 方法可以不用实现,这是在类型识别异常时的处理,默认直接执行基类的处理,由调用对象决定最终结果,若有特殊需要,也可以自己返回一个默认值.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值