【问题标题】:JAXB/Jersey - How To Specify "schemaLocation"JAXB/Jersey - 如何指定“schemaLocation”
【发布时间】:2013-05-10 11:11:30
【问题描述】:

我正在使用 Jersey 创建一个宁静的 Web 服务编组 XML。

如何设置 xsi:schemaLocation?

这个answer 展示了如何直接在 Marshaller 上设置 Marshaller.JAXB_SCHEMA_LOCATION。

我遇到的麻烦是 Jersey 正在将 Java 对象编组为 XML。如何告诉 Jersey 架构位置是什么?

【问题讨论】:

    标签: jaxb jersey


    【解决方案1】:

    您可以为此用例创建MessageBodyWriter。通过ContextResolver 机制,您可以获得与您的域模型关联的JAXBContext。然后你可以从JAXBContext 得到一个Marshaller 并在上面设置JAXB_SCHEMA_LOCATION 并做marshal。

    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;
        }
    
    }
    

    更新

    另一个问题。我的休息资源和提供者之间有什么联系?

    您仍然以相同的方式实现您的资源。 MessageBodyWriter 机制只是一种重写 XML 写入方式的方法。 @Provider 注释是向 JAX-RS 应用程序发出自动注册此类的信号。

    我的资源类将返回一个Foo 对象。我认为我应该实施 MessageBodyWriter&lt;Foo&gt;?

    如果您只想将其应用于Foo 类,则可以将其实现为MessageBodyWriter&lt;Foo&gt;。如果您希望它不仅仅应用于Foo,您可以实现isWriteable 方法以为相应的类返回true。

    【讨论】:

      猜你喜欢
      • 2013-08-28
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多