Servlet 教程 之 Servlet HTTP 状态码 3

简介: 该Servlet教程聚焦于HTTP状态码,示例展示如何向客户端发送407错误,提示"Need authentication!!!". 类名为`showError`的Servlet扩展自`HttpServlet`,重写`doGet`和`doPost`方法。当遇到GET或POST请求时,它会设置HTTP状态码为407并附带错误信息。

Servlet 教程 之 Servlet HTTP 状态码 3

Servlet HTTP 状态码

HTTP 状态码实例

下面的例子把 407 错误代码发送到客户端浏览器,浏览器会显示 "Need authentication!!!" 消息。

// 导入必需的 java 库
import java.io.;
import javax.servlet.
;
import javax.servlet.http.;
import java.util.
;
import javax.servlet.annotation.WebServlet;

@WebServlet("/showError")
// 扩展 HttpServlet 类
public class showError extends HttpServlet {

// 处理 GET 方法请求的方法
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// 设置错误代码和原因
response.sendError(407, "Need authentication!!!" );
}
// 处理 POST 方法请求的方法
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

目录