struts2 自定义全局的类型转换器

1. 定义一个类继承自: com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;

 

DateTypeConverter.java

----------------------------------------------------------------------------------------------------

package org.taink.type.converter;

import java.text.DateFormat;
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) {
        DateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            if (toType == Date.class) { // 当字符向Date 类型转换时
                String[] params = (String[]) value; //request.getParameterValues()
                return simpleDateFormat.parse(params[0]);
            } else if (toType == String.class) { // 当Date 向字符类型转换时
                Date date = (Date) value;
                return simpleDateFormat.format(date);
            }
        } catch (Exception e) {
            System.out.println("-----converter date Exception------");
            e.printStackTrace();
        }
        return null;
    }
}


2.在src 目录 下创建一个xwork-conversion.properties

 

xwork-conversion.properties

----------------------------------------------------------

 

java.util.Date=org.taink.type.converter.DateTypeConverter

 

 

3.action 的代码:

 

EmployeeAction.java

---------------------------------------------------------

package org.taink.struts.action;

import java.util.Date;

public class EmployeeAction {

    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String doAdd() {
        return "success";
    }

    public String execute() {
        return "success";
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值