Java 如何在 JSP 错误处理程序中设置 HTTP 状态代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4387379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:49:17  来源:igfitidea点击:

How to set HTTP status code in JSP error handlers

javajsptomcatjakarta-ee

提问by kayahr

I have a JSP page (in Tomcat) which uses JSP Tags to retrieve some data. But these JSP Tags can throw exceptions (For example when parameter values are invalid). Now I want to implement a nicer error handling for these situation. I failed to find a way to GLOBALLY specify an exception handler (error-page definitions in web.xml don't work for exceptions thrown in a JSP). The only way I found so far is specifiying an errorPage attribute in the page header of ALL JSP-files.

我有一个 JSP 页面(在 Tomcat 中),它使用 JSP 标签来检索一些数据。但是这些 JSP 标记可能会抛出异常(例如,当参数值无效时)。现在我想为这些情况实现更好的错误处理。我没有找到全局指定异常处理程序的方法(web.xml 中的错误页面定义不适用于 JSP 中抛出的异常)。到目前为止,我发现的唯一方法是在所有 JSP 文件的页眉中指定一个 errorPage 属性。

<% page errorPage="/WEB-INF/jsp/errors/500.jsp" %>

Quite annoying to do this for ALL JSPs, but acceptable. But not acceptable is the fact that the error page is always delivered with a HTTP status code of 200. I want a 500 instead. I tried using a servlet as errorPage instead of a JSP and tried to set response.setStatus(500) and also response.sendError(500) but both calls seems to be ignored. So this code prints "200" two times and I have no idea why:

对所有 JSP 执行此操作非常烦人,但可以接受。但不能接受的事实是错误页面总是以 200 的 HTTP 状态代码传送。我想要一个 500。我尝试使用 servlet 作为 errorPage 而不是 JSP 并尝试设置 response.setStatus(500) 和 response.sendError(500) 但两个调用似乎都被忽略了。所以这段代码打印了两次“200”,我不知道为什么:

System.out.println(response.getStatus());
response.setStatus(500);
System.out.println(response.getStatus());

So the question is: How can I set the HTTP status code in JSP error handlers?

所以问题是:如何在 JSP 错误处理程序中设置 HTTP 状态代码?

回答by Teja Kantamneni

You can configure your error pages in web.xml.

您可以在web.xml.

<error-page>
        <error-code>
            500
        </error-code>
        <location>
            /500.jsp
        </location>
    </error-page>

in your 500.jsp, set the directive as <%@ page isErrorPage="true" %>

在您的500.jsp,将指令设置为<%@ page isErrorPage="true" %>

回答by Cosmin Cosmin

Instead of setStatus(500), you'd better use sendError(500)- there are some differences. The config in web.xmlworks fine with sendError, however, if you don't want the config in web.xml, error-pagefrom page directive worked just for exceptions for me, not for HTTP error codes.

而不是setStatus(500),你最好使用sendError(500)- 有一些差异。中的配置与 一起web.xml工作正常sendError,但是,如果您不想要 中的配置web.xml,则error-pagefrom page 指令仅适用于我的异常,而不适用于 HTTP 错误代码。