JAX-RS get entity as JAXB object and as String

情到浓时终转凉″ 提交于 2019-12-05 16:27:39

Turns out it isn't that hard to do this with the JAX-RS API. Here's what I did:

@Path("/transactions")
public class TestResource<X> {

    private Class<X> jaxbClass;

    @POST
    @Path("/{transaction-id}")
    @Consumes("application/xml")
    public Response processPost(@Context Providers providers, @Context HttpHeaders httpHeaders, @PathParam("transaction-id") final long transactionId,
            final String xmlString) throws WebApplicationException, IOException {

        MessageBodyReader<X> reader = providers.getMessageBodyReader(jaxbClass, null, null, MediaType.APPLICATION_XML_TYPE);
        InputStream entityStream = new ByteArrayInputStream(xmlString.getBytes());
        final X xmlObject = reader.readFrom(jaxbClass, null, null, MediaType.APPLICATION_XML_TYPE, httpHeaders.getRequestHeaders(), entityStream);

        //insert logic here

        return Response.ok().build();
    }
}

This will give you the xml as a string and as a JAXB object in just a few lines of code.

As an idea, you can add a servlet filter for your web application that would intercept all requests and capture payload into a thread context where it can be extracted from later on if needed.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!