JAXB/ Jersey - 如何指定 "schemaLocation"

标签 jaxb jersey

我正在使用 Jersey 创建一个 Restful Web 服务编码 XML。

如何设置 xsi:schemaLocation?

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

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

最佳答案

您可以创建一个MessageBodyWriter对于这个用例。通过ContextResolver机制你可以获得JAXBContext与您的域模型相关联。然后你可以得到一个Marshaller来自JAXBContext并设置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;
    }

}

更新

One other question. What is the connection between the my rest resource and the provider?

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

My resource class would return a Foo object. I take it I should be implementing a MessageBodyWriter<Foo>?

您可以将其实现为 MessageBodyWriter<Foo>如果您只想将其应用于 Foo类(class)。如果您希望它不仅仅适用于 Foo您可以实现isWriteable方法为适当的类返回 true。

关于JAXB/ Jersey - 如何指定 "schemaLocation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16572526/

相关文章:

java - 如何处理 JAX-RS 中的意外异常

AngularJS + Jersey RESTful 后端 : Authentication & Authorization

java - Tomcat 在页面加载时给出 500 错误

java - java 客户端如何从 java RESTful Web 服务访问整数数组

spring-mvc - JAX-RS 和 Spring Rest 之间的区别

jaxb - 在 JAX-WS Web 方法中使用接口(interface)

java - 定制 Java 包 JAXB wsimport

java - JAXB 将空列表映射到空集合?

java - 如何配置 Spring 的 RestTemplate 在返回 404 的 HTTP 状态时返回 null

java - FpML 自定义绑定(bind) jaxb