我有一个 Java Web 应用程序,它使用 XML 进行数据交换。我编写了一个 servlet,它使用 HTTP Post 从特定客户端上传 XML 文件。一旦 Post 方法成功完成,它就会向客户端发送 200 OK 消息(使用默认的 Web 服务器 HTTP 状态)。现在我需要在我的应用程序中包含一些 HTTP 状态代码,以便客户端在上传出现问题时获得一些 HTTP 状态消息(例如 400 错误请求、502 错误网关)。我应该如何在我的 Web 应用程序中添加 HTTP 状态代码?请帮我提出建议。谢谢
最佳答案
您可以使用HttpServletResponse#setStatus()
或HttpServletResponse#sendError()
.
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// handle upload
// if error
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
// or
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"An unknown error occurred");
}
这些方法在导致 servlet 容器执行的操作方面有所不同,因此请选择最适合您情况的方法。
setStatus()
If this method is used to set an error code, then the container's error page mechanism will not be triggered.
sendError()
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
状态代码常量列表可在 Field Summary of the javadoc 中找到。 。对于您问题中的代码:
关于java - 基于 Java 服务器的 Web 应用程序中的 HTTP 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6985815/