到目前为止;我们的 servlet 仅支持 application/json
作为输出格式。实际上;我们刚刚将输出返回为 application/json
;不考虑用户的请求:(
继续前进;我们将支持多种输出格式:json/xml 等。
我想知道;实现这一点的行业惯例是什么?我们是否只是从 HttpServletRequest
中读取 getContentType()
并返回适当的数据格式?
最佳答案
getContentType()
返回请求的 Content-Type
header 值。这指定了 HTTP 请求正文的内容。不是它期望作为响应的内容类型。
HTTP 请求可以有 Accept
标题设置
to specify certain media types which are acceptable for the response. Accept headers can be used to indicate that the request is specifically limited to a small set of desired types, as in the case of a request for an in-line image.
用作
Accept: text/plain
// or application/xml or a comma separated list for multiple types (which you would have to parse)
从 HttpServletRequest
中,您可以将其检索为
String responseContentType = request.getHeader("Accept");
HttpServletRequest#getHeader(String)
的 Javadoc 为 here .
显然,如果您的客户端是浏览器,则更改 header 有点困难。
关于java - servlet 支持两种输出格式的标准做法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16801786/