我在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
。很明显它无法工作,因为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");
}
}
但这并没有改变任何事情。没有调用此提供程序的方法。我不确定我是否必须在某处注册。所有其他类都是通过类路径扫描自动找到的,所以我猜这也适用于提供者。
我很确定我做错了什么或者我忘记了什么。任何提示?
答案 0 :(得分:2)
尝试添加@Produces
注释,其中包含"text/html"
fooBar()
方法(我包含JSON
和XML
,因为它听起来像你想要的所有三个)。当我这样做时,你的ResultProvider
被召唤了。如果这对您有用,请告诉我!
@POST
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_HTML })
@Path("fooBar")
public RequestResult fooBar()
{
return new RequestResult();
}