如何创建一个MessageBodyWriter以在RestEasy中将自定义对象作为HTML返回?

我在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格式请求时,我收到错误消息无法找到媒体类型的JAXBContextFinder:text / html.很明显它无法工作,因为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");
    }
}

但这并没有改变任何事情.没有调用此提供程序的方法.我不确定我是否必须在某处注册.所有其他类都是通过类路径扫描自动找到的,所以我猜这也适用于提供者.

我很确定我做错了什么或者我忘记了什么.任何提示?

最佳答案 尝试添加一个包含“text / html”的@Produces注释到你的fooBar()方法(我包括JSON和XML,因为它听起来像你想要的全部三个).当我这样做时,调用了ResultProvider.如果这对您有用,请告诉我!

@POST
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_HTML })
@Path("fooBar")
public RequestResult fooBar()
{
    return new RequestResult();
}
点赞