我有一个 JAX-RS Web 服务 (Jersey),它使用 Eclipselink (MOXy 访问数据库中的一些记录,然后将这些记录编码为 XML,并在对请求的响应中发回给用户。
我遇到的问题是用户想要一种与正在生成的格式不同的格式,即在返回之前应用 XSLT 来转换 XML。
我找到了这个将 XSLT 与 JAXB 结合使用的示例 - http://blog.bdoughan.com/2012/11/using-jaxb-with-xslt-to-produce-html.html
它看起来很有用,但我看不出我应该在哪里拦截 XML 以便在将 XSLT 发送回用户之前应用它。
最佳答案
我会为这个用例实现一个MessageBodyWriter
。在 writeTo
方法的这个实现中,XSLT 样式表将应用于 JAXB 模型以生成所需的 XML:
public void writeTo(Object object, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException {
try {
ContextResolver<JAXBContext> resolver
= providers.getContextResolver(JAXBContext.class, mediaType);
JAXBContext jaxbContext;
if(null == resolver || null == (jaxbContext = resolver.getContext(type))) {
jaxbContext = JAXBContext.newInstance(type);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer(xslt);
JAXBSource source = new JAXBSource(jaxbContext, object);
StreamResult result = new StreamResult(entityStream);
t.transform(source, result);
} catch(JAXBException jaxbException) {
throw new WebApplicationException(jaxbException);
}
}
关于java - 将 XSLT 与 JAXB 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24138133/