gpt4 book ai didi

JAXB/ Jersey - 如何指定 "schemaLocation"

转载 作者:行者123 更新时间:2023-12-04 04:57:37 26 4
gpt4 key购买 nike

我正在使用 Jersey 创建一个安静的 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类。如果您希望它不仅仅适用于 Foo您可以实现到 isWriteable方法为适当的类返回 true。

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com