我正在使用Jersey創建一個寧靜的Web服務marshals XML。JAXB /澤西島 - 如何指定「schemaLocation」
我該如何設置xsi:schemaLocation?
此answer顯示如何直接在Marshaller上設置Marshaller.JAXB_SCHEMA_LOCATION。
我遇到的麻煩是Jersey將Java對象編組爲XML。我如何告訴澤西模式位置是什麼?
我正在使用Jersey創建一個寧靜的Web服務marshals XML。JAXB /澤西島 - 如何指定「schemaLocation」
我該如何設置xsi:schemaLocation?
此answer顯示如何直接在Marshaller上設置Marshaller.JAXB_SCHEMA_LOCATION。
我遇到的麻煩是Jersey將Java對象編組爲XML。我如何告訴澤西模式位置是什麼?
您可以爲此用例創建MessageBodyWriter
。通過ContextResolver
機制,您可以獲得與您的域模型關聯的JAXBContext
。然後你可以從JAXBContext
得到一個Marshaller
,並且設置JAXB_SCHEMA_LOCATION
就可以了,並且執行元帥。其他
package org.example;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.*;
import javax.xml.bind.*;
@Provider
@Produces(MediaType.APPLICATION_XML)
public class FormattingWriter implements MessageBodyWriter<Object>{
@Context
protected Providers providers;
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return true;
}
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);
}
Marshaller m = jaxbContext.createMarshaller();
m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "foo bar");
m.marshal(object, entityStream);
} catch(JAXBException jaxbException) {
throw new WebApplicationException(jaxbException);
}
}
public long getSize(Object t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
}
UPDATE
一個問題。我的休息資源和提供者之間有什麼聯繫?
您仍然以相同的方式實施您的資源。 MessageBodyWriter
機制只是一種重寫如何寫XML的方法。 @Provider
註釋是JAX-RS應用程序發出的一個信號,該類自動註冊。
我的資源分類將返回一個
Foo
對象。我認爲我應該實施MessageBodyWriter<Foo>
?
如果您只希望將它應用於Foo
類,則可以將其實現爲MessageBodyWriter<Foo>
。如果您希望它不僅適用於Foo
,還可以實施isWriteable
方法,以便爲適當的類返回true。