apache cxf 中使用 jax-rs 自定义日期格式?
我一直在谷歌搜索以了解当我在 apache CXF 上使用 jax-rs 时如何自定义日期格式。我查看了代码,似乎它只支持原语、枚举和一个特殊的 hack,假设与 @FormParam 关联的类型有一个带有单个字符串参数的构造函数。如果我想使用 FormParam,这迫使我使用 String 而不是 Date。这有点丑陋。有更好的方法吗?
@POST
@Path("/xxx")
public String addPackage(@FormParam("startDate") Date startDate)
{
...
}
谢谢
I have been googling to figure out how I can customize the Date format when I use jax-rs on apache CXF. I looked at the codes, and it seems that it only support primitives, enum and a special hack that assume the type associated with @FormParam has a constructor with a single string parameter. This force me to use String instead of Date if I want to use FormParam. it is kind of ugly. Is there a better way to do it?
@POST
@Path("/xxx")
public String addPackage(@FormParam("startDate") Date startDate)
{
...
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从 CXF 2.3.2 开始注册 ParameterHandler 就可以了。也始终可以使用 RequestHandler 过滤器覆盖日期值(作为查询的一部分传递等),以使默认 Date(String) 正常工作
starting from CXF 2.3.2 registering ParameterHandler will do it. It is also always possible to override the date value (passed as part of the query, etc) using RequestHandler filters for default Date(String) to work
一种简单的方法是将参数作为 String 并在方法体中解析它以将其转换为 java.util.Date
另一种方法是创建一个类,该类的构造函数接受 String 类型的参数。执行与我在第一种方法中告诉的相同的操作。
这是第二种方法的代码。
希望这有帮助。
One simple apporach is take parameter as String and parse it in method body to convert it to java.util.Date
Another is create one class having constructor takes on parameter of type String. Perform same thing as I told in first approach.
here is the code for second approach.
Hope this helps.
阅读CXF代码(2.2.5)后,这是不可能的,并且使用Date(String)构造函数是硬编码的,所以无论Date(String)支持什么。
After reading the CXF codes (2.2.5), it is not possible, and it is hardcoded to use the Date(String) constructor, so whatever Date(String) support.
在 Apache-cxf 3.0 中,您可以使用
ParamConverterProvider
将参数转换为Date
。以下代码复制自我对此问题的回答。
In Apache-cxf 3.0, you can use a
ParamConverterProvider
to convert a parameter to aDate
.The following code is copied from my answer to this question.