如何在JSP错误处理程序中设置HTTP状态代码 [英] How to set HTTP status code in JSP error handlers

查看:128
本文介绍了如何在JSP错误处理程序中设置HTTP状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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:

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

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

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

推荐答案

您可以在 web.xml 中配置错误页面。

You can configure your error pages in web.xml.

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

500.jsp 中,设置指令为<%@ page isErrorPage =true%>

这篇关于如何在JSP错误处理程序中设置HTTP状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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