JSP HTTP 状态码

在 JSP 里设置状态码、错误页配置、以及常见误用。

Beginner
Key Points用 response.setStatus 改状态行,用 sendError 跳到错误页;两者都要在任何输出之前。

设置状态码

JSP
<%@ page contentType="text/html;charset=UTF-8" %>
<%
    String id = request.getParameter("id");
    if (id == null || id.isBlank()) {
        response.sendError(400, "缺少 id 参数");
        return;
    }
    if (!id.matches("\\d+")) {
        response.sendError(400, "id 必须是数字");
        return;
    }
%>
CodeWhen
200正常返回
201新建资源成功,可带 Location
204成功但没有响应体
301 / 302永久 / 临时跳转
400参数缺失或格式错
401未登录
403已登录无权限
404资源不存在
500未捕获异常

错误页

XML
<error-page>
  <error-code>404</error-code>
  <location>/WEB-INF/errors/404.jsp</location>
</error-page>
<error-page>
  <error-code>500</error-code>
  <location>/WEB-INF/errors/500.jsp</location>
</error-page>
JSP
<%@ page isErrorPage="true" contentType="text/html;charset=UTF-8" %>
<%
    Object code = request.getAttribute("jakarta.servlet.error.status_code");
    Object uri  = request.getAttribute("jakarta.servlet.error.request_uri");
%>
<!DOCTYPE html>
<html><body>
<h1>出错了</h1>
<p>状态码:<%= code %></p>
<p>请求地址:<%= uri %></p>
</body></html>

isErrorPage="true" does two things: it exposes the exception object, and it tells the container this page is an error page so it is not wrapped in another error handler (avoiding infinite recursion).

只在本页处理异常

JSP
<%@ page errorPage="/WEB-INF/errors/500.jsp" %>
<%
    int n = Integer.parseInt(request.getParameter("n"));   // 可能抛异常
%>

errorPage says "where to go if this page fails"; isErrorPage says "I am the handler". The first goes on business pages, the second on error pages.

Setting isErrorPage="true" without any errorPage sends exceptions to the container default page — still 500, but with Tomcat styling and version disclosure. Configure both.

别用 200 表示失败

JSP
<%-- 错误:AJAX 调用方看到 200 会当成功处理 --%>
<% response.setStatus(200); %>
<p>操作失败:库存不足</p>

<%-- 正确 --%>
<% response.sendError(409, "库存不足"); %>

A frontend fetch only enters catch on non-2xx. Returning 200 with an error string forces callers to parse prose to decide success — the most common API smell there is.

Friends & Partners