HttpServletResponse#sendError如何更改ContentType [英] HttpServletResponse#sendError How to change ContentType

查看:207
本文介绍了HttpServletResponse#sendError如何更改ContentType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在创建一个简单的Servlet来回答表单提交.该Servlet接收POST请求,并应响应Application/JSON数据.这运作良好. 现在,我想向我的servlet添加错误管理:如果servlet接收到错误的请求参数,我希望它通过简单的{"error":"ERROR MESSAGE"} JSON响应为客户端回答400 —错误的请求"响应.

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.

我正在使用HttpServletResponse#sendError(int,String)正确发送错误,但是响应的ContentType始终设置为text/html,即使我以前使用过HttpServletResponse#setContentType("application/json").

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.

这是使用Servets发送错误的好方法吗?如何将响应的ContentType强制为application/json?

Is this the good way to send error using Servets ? How can I force the ContentType of the response to application/json?

我的测试Servlet的doPost()方法的示例代码:

EDIT : Sample code of the doPost() method of my test Servlet :

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);
}

推荐答案

有效

使用指定的状态向客户端发送错误响应,并 清除缓冲区.服务器默认为创建响应 看起来像一个HTML格式的服务器错误页面,其中包含指定的 消息,将内容类型设置为"text/html".

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".

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.

这意味着:设置内容类型,写入缓冲区,然后调用sendError(400).

This means: set the content type, write to the buffer, call sendError(400).

这篇关于HttpServletResponse#sendError如何更改ContentType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆