简体   繁体   中英

CXF/JAXB fails at marshalling primitive long return value

I have a simple CXF method that returns a long

  @GET
  @Path("/count/{foo}/{bar}")
  long count(@PathParam("foo") String foo, @PathParam("bar") String bar)

I have a CXF server with JAXB setup for it

<jaxrs:server id="myServer" address="/">
    <jaxrs:providers>
      <bean id="jaxbProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
        <property name="singleJaxbContext" value="true" />
        <property name="skipJaxbChecks" value="true" />
        <property name="validateOutput" value="false" />
      </bean>
    </jaxrs:providers>
    <jaxrs:serviceBeans>
      <ref bean="myServiceImpl" />
    </jaxrs:serviceBeans>
</jaxrs:server>

But when I call this method, the server fails at marshalling the result :

Caused by: com.sun.istack.SAXException2: unable to marshal type "java.lang.Long" as an element because it is missing an @XmlRootElement annotation

How come CXF is not able to marshal a long ? Thanks for your help

EDIT

I am actually writing a mockup implementation of an existing service (for test purposes). I have no control on the API of the existing service. And its current implementation returns something like

Response-Code: 200
Encoding: ISO-8859-1
Content-Type: application/xml
Headers: {connection=[close], Content-Length=[3], content-type=[application/xml], Date=[Wed, 23 Jul 2014 08:00:31 GMT]}
Payload: 121

Which is no real XML i agree. But the current client does not complain either, and does no contain any magic for it.

Why do you need to create xml structure for a single return value, You retrun it as text and add Annotation Produces with return type content as plain/text.

@GET
@Produces("text/plain")
@Path("/count/{foo}/{bar}")
long count(@PathParam("foo") String foo, @PathParam("bar") String bar)

If you are using cxf client you can read it as long as follows

Response response = client.get();
response.readEntity(Long.class);

EDIT

Remove the jaxrs:providers, cxf internally handles jaxb conversions by default

<jaxrs:server id="myServer" address="/">
    <jaxrs:serviceBeans>
      <ref bean="myServiceImpl" />
    </jaxrs:serviceBeans>
</jaxrs:server>

Here is the below code I tested, however when I added the provider it gives error.

@Path("/add")
    @Produces("application/xml")
    @GET
    public Long add(@QueryParam("v1")int v1, @QueryParam("v2")int v2){

        long result =v1+v2;
        return result;

    }


    @Path("/subtract")
    @Produces("application/xml")
    @GET
    public Output subtract(@QueryParam("v1")int v1, @QueryParam("v2")int v2){

        Output out = new Output();
        out.setResult(v1-v2);
        return out;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM