Jersey2为Jackson和JAXB提供内置支持。 但是默认情况下不支持Jibx。 要将Jibx与Jersey2结合使用,我们将XML输入作为流,并在接收到请求之后,使用Jibx对其进行解析。 但是实际上,有更好的方法可以使用MessageBodyReader和MessageBodyWriter API来实现相同目的。 这是可以实现的方式:
- 为使用Jibx的XML定义新的提供程序
- 向Jersey ResourceConfig注册
@Provider
public class JibxXmlProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object> {
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
if(!MediaType.APPLICATION_XML_TYPE.equals(mediaType)){
return false;
}
try {
BindingDirectory.getFactory( type );
} catch (JiBXException e) {
return false;
}
return true;
}
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType ) {
if(!MediaType.APPLICATION_XML_TYPE.equals(mediaType)){
return false;
}
try {
BindingDirectory.getFactory( type );
} catch (JiBXException e) {
return false;
}
return true;
}
public Object readFrom(Class<Object> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
try {
IBindingFactory factory = BindingDirectory.getFactory( type );
IUnmarshallingContext context = factory.createUnmarshallingContext();
return context.unmarshalDocument( entityStream, null );
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void writeTo(Object obj, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> headers, OutputStream outputStream)
throws IOException, WebApplicationException {
try {
IBindingFactory factory = BindingDirectory.getFactory( type );
IMarshallingContext context = factory.createMarshallingContext();
context.marshalDocument( obj, "UTF-8", null, outputStream );
}
catch ( Exception e ) {
e.printStackTrace();
}
}
public long getSize(Object obj, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType ) {
return -1;
}
}
定义了此类后,请按照以下步骤在Jersey上注册:
public class JerseyResourceInitializer extends ResourceConfig {
public JerseyResourceInitializer() {
packages(true, "com.adaequare.processing.service");
// This line registers JibxXmlProvider as a new provider.
register(JibxXmlProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
}
}
完成此配置后,每当有新请求出现时,就会调用JibxXmlProvider的isReadable方法。 如果计算结果为true,则将调用readFrom进行对象转换。
希望这可以帮助!
翻译自: https://www.javacodegeeks.com/2014/04/jibx-jersey2-integration.html