隨筆-16  評論-84  文章-1  trackbacks-0

          在項目中使用Apache開源的Services Framework CXF來發布WebService,CXF能夠很簡潔與Spring Framework 集成在一起,在發布WebService的過程中,發布的接口的入參有些類型支持不是很好,比如Timestamp和Map。這個時候我們就需要編寫一些適配來實行類型轉換。

          Timestamp:

           1/**
           2 * <java.sql.Timestamp類型轉換>
           3 * <功能詳細描述>
           4 * 
           5 * @author  Owen
           6 * @version  [版本號, 2010-11-26]
           7 * @see  [相關類/方法]
           8 * @since  [產品/模塊版本]
           9 */

          10public class TimestampAdapter extends XmlAdapter<String, Timestamp>
          11{
          12    /** <一句話功能簡述>
          13     * <功能詳細描述>
          14     * @param time
          15     * @return
          16     * @throws Exception
          17     * @see [類、類#方法、類#成員]
          18     */

          19    public String marshal(Timestamp time)
          20        throws Exception
          21    {
          22        return DateUtil.timestamp2Str(time);
          23    }

          24    
          25    /** <一句話功能簡述>
          26    * <功能詳細描述>
          27    * @param v
          28    * @throws Exception
          29    * @see [類、類#方法、類#成員]
          30    */

          31    public Timestamp unmarshal(String str)
          32        throws Exception
          33    {
          34        return DateUtil.str2Timestamp(str);
          35    }

          36    
          37}


          DateUtil

            1/*
            2 * 文 件 名:  DateUtil.java
            3 * 版    權:  4 Dream Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
            4 * 描    述:  <描述>
            5 * 修 改 人:  Owen 
            6 * 修改時間:  2010-11-5
            7 * 跟蹤單號:  <跟蹤單號>
            8 * 修改單號:  <修改單號>
            9 * 修改內容:  <修改內容>
           10 */

           11package com.osoft.portal.common.util.commons;
           12
           13import java.sql.Timestamp;
           14import java.text.ParseException;
           15import java.text.SimpleDateFormat;
           16import java.util.Date;
           17
           18import org.apache.log4j.Logger;
           19
           20/**
           21 * <一句話功能簡述>
           22 * <功能詳細描述>
           23 * 
           24 * @author  Owen
           25 * @version  [版本號, 2010-11-5]
           26 * @see  [相關類/方法]
           27 * @since  [產品/模塊版本]
           28 */

           29public class DateUtil
           30{
           31    /**
           32     * 注釋內容
           33     */

           34    private static final Logger log = Logger.getLogger(DateUtil.class);
           35    
           36    /**
           37     * 默認日期格式
           38     */

           39    private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
           40    
           41    /** <默認構造函數>
           42     */

           43    private DateUtil()
           44    {
           45    }

           46    
           47    /** <字符串轉換成日期>
           48     * <如果轉換格式為空,則利用默認格式進行轉換操作>
           49     * @param str 字符串
           50     * @param format 日期格式
           51     * @return 日期
           52     * @see [類、類#方法、類#成員]
           53     */

           54    public static Date str2Date(String str, String format)
           55    {
           56        if (null == str || "".equals(str))
           57        {
           58            return null;
           59        }

           60        //如果沒有指定字符串轉換的格式,則用默認格式進行轉換
           61        if (null == format || "".equals(format))
           62        {
           63            format = DEFAULT_FORMAT;
           64        }

           65        SimpleDateFormat sdf = new SimpleDateFormat(format);
           66        Date date = null;
           67        try
           68        {
           69            date = sdf.parse(str);
           70            return date;
           71        }

           72        catch (ParseException e)
           73        {
           74            log.error("Parse string to date error!String : " + str);
           75        }

           76        
           77        return null;
           78    }

           79    
           80    /** <一句話功能簡述>
           81     * <功能詳細描述>
           82     * @param date 日期
           83     * @param format 日期格式
           84     * @return 字符串
           85     * @see [類、類#方法、類#成員]
           86     */

           87    public static String date2Str(Date date, String format)
           88    {
           89        if (null == date)
           90        {
           91            return null;
           92        }

           93        SimpleDateFormat sdf = new SimpleDateFormat(format);
           94        return sdf.format(date);
           95    }

           96    
           97    /** <時間戳轉換為字符串>
           98     * <功能詳細描述>
           99     * @param time
          100     * @return
          101     * @see [類、類#方法、類#成員]
          102     */

          103    public static String timestamp2Str(Timestamp time)
          104    {
          105        Date date = new Date(time.getTime());
          106        return date2Str(date, DEFAULT_FORMAT);
          107    }

          108    
          109    /** <一句話功能簡述>
          110     * <功能詳細描述>
          111     * @param str
          112     * @return
          113     * @see [類、類#方法、類#成員]
          114     */

          115    public static Timestamp str2Timestamp(String str)
          116    {
          117        Date date = str2Date(str, DEFAULT_FORMAT);
          118        return new Timestamp(date.getTime());
          119    }

          120}

          121



          在具體的Java Bean 中,通過@XmlJavaTypeAdapter注解來通知CXF進行類型轉換,具體請看User中的屬性registerDate的getter 和setter

            1package com.osoft.portal.system.model;
            2
            3import java.io.Serializable;
            4import java.sql.Timestamp;
            5
            6import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
            7
            8import com.osoft.portal.common.util.commons.DateUtil;
            9import com.osoft.portal.remote.convert.TimestampAdapter;
           10
           11/**
           12 * <一句話功能簡述>
           13 * <功能詳細描述>
           14 * 
           15 * @author  Owen
           16 * @version  [版本號, 2010-11-1]
           17 * @see  [相關類/方法]
           18 * @since  [產品/模塊版本]
           19 */

           20public class User implements Serializable
           21{
           22    private static final long serialVersionUID = -6449817937177158567L;
           23    
           24    /**
           25     * 用戶標示
           26     */

           27    private long id;
           28    
           29    /**
           30     * 登錄賬號
           31     */

           32    private String username;
           33    
           34    /**
           35     * 登錄密碼
           36     */

           37    private String password;
           38    
           39    /**
           40     * 真實姓名
           41     */

           42    private String realName;
           43    
           44    /**
           45     * 性別
           46     */

           47    private String sex;
           48    
           49    /**
           50     * 注冊日期
           51     */

           52    private Timestamp registerDate;
           53    
           54    /**
           55     * 用戶狀態
           56     */

           57    private String state;
           58    
           59    /** <默認構造函數>
           60     */

           61    public User()
           62    {
           63    }

           64    
           65    public long getId()
           66    {
           67        return id;
           68    }

           69    
           70    public void setId(long id)
           71    {
           72        this.id = id;
           73    }

           74    
           75    public String getUsername()
           76    {
           77        return username;
           78    }

           79    
           80    public void setUsername(String username)
           81    {
           82        this.username = username;
           83    }

           84    
           85    public String getPassword()
           86    {
           87        return password;
           88    }

           89    
           90    public void setPassword(String password)
           91    {
           92        this.password = password;
           93    }

           94    
           95    public String getRealName()
           96    {
           97        return realName;
           98    }

           99    
          100    public void setRealName(String realName)
          101    {
          102        this.realName = realName;
          103    }

          104    
          105    public String getSex()
          106    {
          107        return sex;
          108    }

          109    
          110    public void setSex(String sex)
          111    {
          112        this.sex = sex;
          113    }

          114    
          115    @XmlJavaTypeAdapter(TimestampAdapter.class)
          116    public Timestamp getRegisterDate()
          117    {
          118        return registerDate;
          119    }

          120    
          121    public void setRegisterDate(@XmlJavaTypeAdapter(TimestampAdapter.class) Timestamp registerDate)
          122    {
          123        this.registerDate = registerDate;
          124    }

          125    
          126    public String getState()
          127    {
          128        return state;
          129    }

          130    
          131    public void setState(String state)
          132    {
          133        this.state = state;
          134    }

          135    
          136    /** <一句話功能簡述>
          137     * <功能詳細描述>
          138     * @return
          139     * @see [類、類#方法、類#成員]
          140     */

          141    public String toString()
          142    {
          143        StringBuilder build = new StringBuilder();
          144        build.append("Real Name: " + this.getRealName() + ",Register Date: "
          145            + DateUtil.timestamp2Str(this.getRegisterDate()));
          146        return build.toString();
          147    }

          148    
          149}

          150


          OK,這個時候CXF解析Java Bean User的時候,解析到@XmlJavaTypeAdapter注解時候就會以TimestampAdapter這個適配器來進行Timestamp與String之間的轉換。


          Map:

          這里貼下上一個項目中java.util.Map寫的轉換器,參考javaeye上一個網友提示的,直接用xstream將Map轉換成String

           1/**
           2 * <數據模型轉換>
           3 * <Map<String,Object> 與 String之間的轉換>
           4 * 
           5 * @author  Owen
           6 * @version  [版本號, Apr 28, 2010]
           7 * @see  [相關類/方法]
           8 * @since  [產品/模塊版本]
           9 */

          10@XmlType(name = "MapAdapter")
          11@XmlAccessorType(XmlAccessType.FIELD)
          12public class MapAdapter extends XmlAdapter<String, Map<String, Object>>
          13{
          14    
          15    /**
          16     * Convert a bound type to a value type.
          17     * 轉換JAXB不支持的對象類型為JAXB支持的對象類型
          18     *
          19     * @param map map
          20     *      The value to be convereted. Can be null.
          21     * @return String   
          22     * @throws Exception
          23     *      if there's an error during the conversion. The caller is responsible for
          24     *      reporting the error to the user through {@link javax.xml.bind.ValidationEventHandler}.
          25     */

          26    public String marshal(Map<String, Object> map)
          27        throws Exception
          28    {
          29        XStream xs = new XStream(new DomDriver());
          30        return xs.toXML(map);
          31    }

          32    
          33    /**
          34     * Convert a value type to a bound type.
          35     * 轉換JAXB支持的對象類型為JAXB不支持的的類型
          36     *
          37     * @param model
          38     *      The value to be converted. Can be null.
          39     * @return Map<String,Object>
          40     * @throws Exception
          41     *      if there's an error during the conversion. The caller is responsible for
          42     *      reporting the error to the user through {@link javax.xml.bind.ValidationEventHandler}.
          43     */

          44    @SuppressWarnings("unchecked")
          45    public Map<String, Object> unmarshal(String model)
          46        throws Exception
          47    {
          48        XStream xs = new XStream(new DomDriver());
          49        return (HashMap)xs.fromXML(model);
          50    }

          51    
          52}
          posted on 2010-11-27 14:28 absolute 閱讀(3427) 評論(1)  編輯  收藏

          評論:
          # re: 讓Apache CXF 支持傳遞java.sql.Timestamp和java.util.HashMap類型 2014-08-19 10:44 | David房
          謝謝,解決了我的問題,但是@XmlJavaTypeAdapter(TimestampAdapter.class)這段加在get/set前面會報有多個屬性的錯,加在private Timestamp registerDate;前面就ok了。  回復  更多評論
            

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 阿鲁科尔沁旗| 武汉市| 葫芦岛市| 墨脱县| 自贡市| 原阳县| 新和县| 宣恩县| 岐山县| 阳曲县| 凤冈县| 惠水县| 太谷县| 红原县| 稻城县| 巫山县| 万州区| 漳州市| 定兴县| 油尖旺区| 旬邑县| 广南县| 广灵县| 衡东县| 奇台县| 瑞金市| 旬邑县| 阜城县| 涟源市| 古蔺县| 玛多县| 陈巴尔虎旗| 永昌县| 瓦房店市| 太保市| 富裕县| 全南县| 闽清县| 海盐县| 阜阳市| 仙居县|