我在Tomcat中使用RestEasy和Spring . 我有一个简单的控制器方法,我想通过Ajax(使用JSON或XML响应)和标准浏览器请求(使用HTML作为响应)使用 . 它使用简单的返回数据类型,如字符串,但我需要返回一个自定义对象:
@POST
@Path("fooBar")
public RequestResult fooBar()
{
return new RequestResult();
}
这是RequestResult对象(只是演示的虚拟实现):
@XmlRootElement(name = "result")
public final class RequestResult
{
@XmlAttribute
public boolean getWhatever()
{
return "whatever";
}
}
它在以JSON或XML请求它时有效,但在以HTML格式请求时,我收到错误消息 Could not find JAXBContextFinder for media type: text/html
. 它's clear that it can'工作因为RestEasy不知道如何将此对象转换为HTML . 所以我添加了这个测试MessageBodyWriter:
@Provider
@Produces("text/html")
public class ResultProvider implements MessageBodyWriter<RequestResult>
{
@Override
public boolean isWriteable(final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType)
{
return true;
}
@Override
public long getSize(final RequestResult t, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType)
{
return 4;
}
@Override
public void writeTo(final RequestResult t, final Class<?> type, final Type genericType,
final Annotation[] annotations, final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream)
throws IOException, WebApplicationException
{
final PrintWriter writer = new PrintWriter(entityStream);
writer.println("Test");
}
}
但这并没有改变任何事情 . 没有调用此提供程序的方法 . 我不确定我是否必须在某处注册 . 所有其他类都是通过类路径扫描自动找到的,所以我猜这也适用于提供者 .
我很确定我做错了什么或者我忘记了什么 . 任何提示?
1 回答
尝试添加一个
@Produces
注释,其中包含"text/html"
到您的fooBar()
方法(我包括JSON
和XML
,因为它听起来像你想要的全部三个) . 当我这样做时,你的ResultProvider
被召唤了 . 如果这对您有用,请告诉我!