java - servlet 支持两种输出格式的标准做法

标签 java servlets

到目前为止;我们的 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/

相关文章:

java - J2EE 和 Angular HTTP POST servlet

java - Gson解析为包含JsonArray的对象

java - java中解析多个json对象

java - Tomcat 服务器正在启动,但当我打开它时只显示空白页面

Java servlet 在服务器重启后跳过一个数据库读取

java servlet : stream image

java - 无法在 spring-servlet.xml 文件中创建 org.apache.commons.dbcp.BasicDataSource 的 bean

java - 如何避免 Hibernate 为 OneToMany 的更新生成两个查询?

java - 是否可以在 maven 中使用 apache cxf 将 web 服务客户端代码生成到特殊包?

java - 将 double 转换为保留 2 位小数的字符串