cxf jax-rs:如何将基本类型编组为 XML?
我有一个 cxf JAX-RS 服务,如下所示。当我提交请求类型为“application/xml”的请求时,我希望 cxf 自动将我的返回值转换为 xml。这适用于方法 getData
,但不适用于其他 2 个方法。其他 2 个方法返回返回值的简单字符串表示形式,例如 2.0
或 true
。如何让 cxf 返回所有 3 种方法的 XML 文档?
@WebService
@Consumes("application/xml")
@Produces("application/xml")
public interface MyServiceInterface {
final static String VERSION = "2.0";
@WebMethod
@GET
@Path("/version")
String getVersion();
@WebMethod
@GET
@Path("/data/{user}")
Data[] getData(@PathParam("user") String username) throws IOException;
@WebMethod
@GET
@Path("/user/{user}")
boolean doesUserExist(@PathParam("user") String username);
}
I have a cxf JAX-RS service which looks something like the one below. When I submit a request with requested type "application/xml" I would expect that cxf automatically converts my return value into xml. This works for the method getData
, but not for the other 2 methods. The other 2 methods return a simple String representation of the return value such as 2.0
or true
. How do I get cxf to return a XML document for all 3 methods?
@WebService
@Consumes("application/xml")
@Produces("application/xml")
public interface MyServiceInterface {
final static String VERSION = "2.0";
@WebMethod
@GET
@Path("/version")
String getVersion();
@WebMethod
@GET
@Path("/data/{user}")
Data[] getData(@PathParam("user") String username) throws IOException;
@WebMethod
@GET
@Path("/user/{user}")
boolean doesUserExist(@PathParam("user") String username);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,
String
和boolean
都没有 XML 文档的自然表示形式。 XML 需要一个外部元素,CXF 和 JAXB(XML 绑定层)都不知道它应该是什么。最简单的方法是在一个带有 JAXB 注释的包装器中返回基本类型:
另一种方法是注册知道如何将字符串和布尔值转换为 XML 的提供程序,但这很混乱,并且会以意想不到的方式影响整个应用程序你真的不应该对简单类型这样做,好吗?
The issue is that neither
String
norboolean
has a natural representation as an XML document; XML requires an outer element, and neither CXF nor JAXB (the XML binding layer) knows what it should be.The simplest method is to return the basic type inside a little JAXB-annotated wrapper:
The other way of doing this would be to register providers that know how to convert strings and booleans into XML, but that's messy and affects your whole application in unexpected ways and you really shouldn't do that for simple types, OK?