pde*_*d59 5 java servlets java-ee
我现在正在创建一个简单的Servlet来回答表单子目录.此servlet接收POST请求,并应响应Application/JSON数据.这很好用.我现在想要向我的servlet添加错误管理:如果servlet收到错误的请求参数,我希望它通过简单的{"error":"ERROR MESSAGE"}JSON响应回答客户端400 - "错误请求" 响应.
我正在使用HttpServletResponse#sendError(int,String)正确发送错误,但ContentType响应的始终设置为text/html,即使我HttpServletResponse#setContentType("application/json")之前使用过.
这是使用Servets发送错误的好方法吗?我如何强制ContentType响应application/json?
编辑:我的测试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);
}
Run Code Online (Sandbox Code Playgroud)
Jas*_*eck 17
我想在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!
Run Code Online (Sandbox Code Playgroud)
flushBuffer对于将响应标记为已提交是至关重要的,就像sendError那样.起初我尝试在输出流上调用close,但是会发生什么情况是我的过滤器会运行然后JAX-RS资源将继续正常运行,然后我会得到错误消息并且正常响应与200状态连接在一起码!
resetBuffer就是为了防止其他任何设置标题或在此过滤器之前写入一些内容.
这按规定工作:
使用指定的状态向客户端发送错误响应并清除缓冲区。服务器默认创建的响应看起来像包含指定消息的 HTML 格式的服务器错误页面,将内容类型设置为“text/html”。
HttpServletResponse.sendError(int)
Run Code Online (Sandbox Code Playgroud)
另一方面没有这个限制/功能。
使用指定的状态代码向客户端发送错误响应并清除缓冲区。
这意味着:设置内容类型,写入缓冲区,调用sendError(400).
| 归档时间: |
|
| 查看次数: |
11948 次 |
| 最近记录: |