2010-05-14 103 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); 
    } 

}