2010-05-14 105 views
4

我一直在使用googling來弄清楚如何在apache CXF上使用jax-rs時自定義日期格式。我查看了代碼,它似乎只支持基元,枚舉和特殊的hack,假設與@FormParam關聯的類型具有帶單個字符串參數的構造函數。如果我想使用FormParam,這迫使我使用String而不是Date。這有點醜。有沒有更好的方法來做到這一點?在apache cxf中使用jax-rs自定義日期格式?

@POST 
@Path("/xxx") 
public String addPackage(@FormParam("startDate") Date startDate) 
    { 
     ... 
    } 

感謝

回答

0

閱讀CXF代碼(2.2.5)之後,它是不可能的,它是硬編碼到使用日期(String)構造,所以無論日期(字符串)的支持。

4

從CXF開始2.3.2註冊ParameterHandler會做到這一點。也可以使用RequestHandler過濾器覆蓋日期值(作爲查詢的一部分傳遞),以使用默認日期(字符串)工作

4

一個簡單的應用是將參數作爲字符串並將其解析爲方法體將其轉換爲java.util.Date

另一種是創建一個具有構造函數的類,它接受String類型的參數。按照我在第一種方法中所講的完成同樣的事情

這裏是第二種方法的代碼。

@Path("date-test") 
public class DateTest{ 

    @GET 
    @Path("/print-date") 
    public void printDate(@FormParam("date") DateAdapter adapter){ 
     System.out.println(adapter.getDate()); 
    } 

    public static class DateAdapter{ 
     private Date date; 
     public DateAdapter(String date){ 
      try { 
       this.date = new SimpleDateFormat("dd/MM/yyyy").parse(date); 
      } catch (Exception e) { 

      } 
     } 

     public Date getDate(){ 
      return this.date; 
     } 
    } 
} 

希望這會有所幫助。

0

在Apache-cxf 3.0中,您可以使用ParamConverterProvider將參數轉換爲Date

以下代碼複製自my answer to this question

public class DateParameterConverterProvider implements ParamConverterProvider { 

    @Override 
    public <T> ParamConverter<T> getConverter(Class<T> type, Type type1, Annotation[] antns) { 
     if (Date.class.equals(type)) { 
      return (ParamConverter<T>) new DateParameterConverter(); 
     } 
     return null; 
    } 

} 

public class DateParameterConverter implements ParamConverter<Date> { 

    public static final String format = "yyyy-MM-dd"; // set the format to whatever you need 

    @Override 
    public Date fromString(String string) { 
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); 
     try { 
      return simpleDateFormat.parse(string); 
     } catch (ParseException ex) { 
      throw new WebApplicationException(ex); 
     } 
    } 

    @Override 
    public String toString(Date t) { 
     return new SimpleDateFormat(format).format(t); 
    } 

}