java HttpServletResponse#sendError 如何更改 ContentType
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14459045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpServletResponse#sendError How to change ContentType
提问by pdegand59
I'm now creating a simple Servlet to answer a form submition. This servlet receive POST request and should response Application/JSON datas. This is working well.
I want now to add errors managment to my servlet: If the servlet receive bad request parameters, I want it to answer the client a 400 — "Bad Request" response with a simple {"error":"ERROR MESSAGE"}
JSON response.
我现在正在创建一个简单的 Servlet 来回答表单提交。此 servlet 接收 POST 请求并应响应应用程序/JSON 数据。这运行良好。我现在想向我的 servlet 添加错误管理:如果 servlet 收到错误的请求参数,我希望它用简单的{"error":"ERROR MESSAGE"}
JSON 响应回答客户端 400 —“错误请求”响应。
I'm using the HttpServletResponse#sendError(int,String)
to correctly send the error but the ContentType
of the response is always set to text/html
, even though I used HttpServletResponse#setContentType("application/json")
before.
我正在使用HttpServletResponse#sendError(int,String)
来正确发送错误,但ContentType
响应的 始终设置为text/html
,即使我HttpServletResponse#setContentType("application/json")
以前使用过。
Is this the good way to send error using Servets ? How can I force the ContentType
of the response to application/json
?
这是使用 Servets 发送错误的好方法吗?我怎样才能强制ContentType
响应的application/json
?
EDIT : Sample code of the doPost() method of my test Servlet :
编辑:我的测试 Servlet 的 doPost() 方法的示例代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("{\"error\":1}");
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
采纳答案by Marcel St?r
That works as specified:
这按规定工作:
Sends an error response to the client using the specified status and clears the buffer. The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html".
使用指定的状态向客户端发送错误响应并清除缓冲区。服务器默认创建的响应看起来像包含指定消息的 HTML 格式的服务器错误页面,将内容类型设置为“text/html”。
HttpServletResponse.sendError(int)
on the other hand does not have this restriction/feature.
另一方面没有这个限制/功能。
Sends an error response to the client using the specified status code and clearing the buffer.
使用指定的状态代码向客户端发送错误响应并清除缓冲区。
This means: set the content type, write to the buffer, call sendError(400)
.
这意味着:设置内容类型,写入缓冲区,调用sendError(400)
.
回答by Jason Winnebeck
I recently had this issue when wanting to send error messages inside of a JAX-RS application. sendError would always return text/html, per the spec. I had to do the following, given a HttpServletResponse response
:
我最近在想在 JAX-RS 应用程序内部发送错误消息时遇到了这个问题。根据规范,sendError 将始终返回 text/html。给定一个,我必须执行以下操作HttpServletResponse response
:
response.resetBuffer();
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setHeader("Content-Type", "application/json");
response.getOutputStream().print("{\"errorMessage\":\"You can't use this!\"}")
response.flushBuffer() //marks response as committed -- if we don't do this the request will go through normally!
The flushBuffer is critical to mark the response as committed, as sendError does. At first I tried just calling close on the output stream, but what would happen is my filter would run then the JAX-RS resource would continue to run normally, then I'd get the error message AND the normal response concatenated together with 200 status code!
flushBuffer 对于将响应标记为已提交至关重要,就像 sendError 一样。起初我只是尝试在输出流上调用 close,但会发生什么是我的过滤器将运行然后 JAX-RS 资源将继续正常运行,然后我会收到错误消息和与 200 状态连接在一起的正常响应代码!
resetBuffer is there just in case anything else has set headers or written some content before this filter.
resetBuffer 是为了以防万一在此过滤器之前设置了标题或写入了一些内容。
回答by Yunwen
Instead of calling response.sendError(int), use response.setStatus(int).
不要调用 response.sendError(int),而是使用 response.setStatus(int)。