dropwizard:从同一个类中生成html和json [英] dropwizard: produce both html and json from the same class
问题描述
有没有一种方法可以控制客户端的输出格式?
我有一个类,
@Produces(MediaType.TEXT_HTML)
我想要
我可以逐字复制类,只替换 @Path 和 @Produces 注释,但这看起来很浪费。
我想知道客户是否可以添加& content之类的内容-type = application / json 到URL,并让我的服务器使用json而不是html进行响应?
您将需要同时提供HTML和JSON来注释资源:
@Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_JSON} )
然后只需确保您具有 MessageBodyWriter
为处理方法的返回类型而注册的实现。 Dropwizard的 JacksonMessageBodyProvider
应该处理JSON;如果您使用的是Dropwizard视图,则 ViewMessageBodyWriter
应该可以处理其余的内容。如果您的客户端在请求的 Accept
标头中具有 application / json
,则Jersey将与客户端进行内容协商。 / p>
Is there a way to control the output format from the client side?
I have a class which
@Produces(MediaType.TEXT_HTML)
and I want it to produce json when the client requests.
I can copy the class verbatim, replacing only the @Path and @Produces annotations, but this looks like a total waste.
I wonder if the client could append something like &content-type=application/json to the URL and have my server respond with json instead of html?
You'll need to annotate the resources as providing both HTML and JSON:
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
Then just make sure you have MessageBodyWriter
implementations registered to handle the method's return type. Dropwizard's JacksonMessageBodyProvider
should handle the JSON; if you're using Dropwizard Views, ViewMessageBodyWriter
should handle the rest. Jersey will do the content negotiation with the client, provided your client has application/json
in the request's Accept
header.
这篇关于dropwizard:从同一个类中生成html和json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!