我是泽西框架JAX-RS的新手。我有一个要求。
我读了对Jaxb对象的XML响应。
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("http://localhost:8080/rest/");
Response response = webTarget.path("provider").request(MediaType.APPLICATION_XML).get();
ProviderBean providerBean = response.readEntity(ProviderBean.class); //My JAXB object. Will be used as a model for Hibernate
我在Hibernate中使用相同的ProviderBean Jaxb对象作为持久模型。
ProviderBean.java
@Entity
@Table(name="PROVIDER")
@XmlRootElement(name = "response")
public class ProviderBean{
}
现在,我可以使用hibernate来持久保存Jaxb对象。但是我需要客户端发送实际的XML响应以将其存储在DB表中。
<?xml version="1.0" encoding="UTF-8"?>
<response>
<provider>
<provider_id>123</provider_id>
<provider_name>abc</provider_name>
</provider>
</response>
我必须捕获此XML响应并将其存储在DB表中,如“TRANSACTION”表中名为“RESPONSE_XML”的列中所示。
解决方案我想: 可以通过将相同的Jaxb对象编组到xml。这里的问题是,由于相同的对象用于持久性,我觉得它可能很复杂。
我知道响应一旦读取就无法再次读取。我尝试在“Response”对象下搜索所有方法。有没有解决方法?
任何建议或帮助将不胜感激。感谢。
答案 0 :(得分:0)
创建请求/响应过滤器(取决于您要存储XML的那一侧),以便您访问InputStream
:
@PreMatching
@Priority(Integer.MIN_VALUE)
public class PersistenceFilter implements ContainerRequestFilter, ClientResponseFilter {
@Override
public void filter(final ClientRequestContext requestContext,
final ClientResponseContext responseContext)
throws IOException {
// client-side
responseContext.setEntityStream(
persistInboundEntity(responseContext.getEntityStream()));
}
@Override
public void filter(final ContainerRequestContext requestContext)
throws IOException {
// server-side
requestContext.setEntityStream(
persistInboundEntity(requestContext.getEntityStream()));
}
private InputStream persistInboundEntity(InputStream stream)
throws IOException {
if (!stream.markSupported()) {
stream = new BufferedInputStream(stream);
}
// Store InputStream / Create an byte array.
// Reset it so Jersey can read it too.
stream.reset();
return stream;
}
}
不要忘记在最后重置流,以便泽西也可以阅读它。
答案 1 :(得分:0)
在尝试了几种方法之后,最后在参考规范之后我找到了一个解决我想要的简单解决方案。在这里,
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("http://localhost:8080/rest/");
Response response = webTarget.path("provider").request(MediaType.APPLICATION_XML).get();
boolean bufferSts = response.bufferEntity(); // This is the solution im looking
ProviderBean providerBean = response.readEntity(ProviderBean.class); //My JAXB object. Will be used as a model for Hibernate
String xmlRes = response.readEntity(String.class); // I can read the response again
更多详情:https://java.net/projects/jax-rs-spec/sources/git/show/src/jax-rs-api/src/main/java/javax/ws/rs/core/Response.java - bufferEntity