在我的应用程序中,我想返回错误代码并在服务器上设置错误消息。这是我使用的:
response.setStatus(530);
response.sendError(530, e.getMessage());
当我返回这样的自定义错误时,应用程序引擎始终发送包含在默认 html 模板中的错误代码和状态。在 JavaScript 中:
$(document).ajaxError(function (event, request, settings) {
// request.statusText is always "Internal Server Error"
// and not my custom status message
// request.responseText is an html string
});
顺便说一句,在开发服务器中情况有所不同。 statusText 是我的自定义错误文本
最佳答案
在 web.xml 文件中,您可以指定要针对特定错误代码提供服务的 jsp:
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/errors/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/jsp/errors/500.jsp</location>
</error-page>
jsp 将根据需要呈现。
请注意,这在本地开发服务器中无法正常工作,您需要进行部署才能看到它的运行情况。为了帮助开发,您可以直接将错误页面作为jsp加载。
错误页面渲染仅在您resp.sendError(code)
时发生 - 如果您只是执行resp.setStatus(code, message)
,servlet容器将不会处理错误像这样。例如,这使您仍然可以返回 json 和 ajax 调用的错误代码。
如果您没有指定页面,servlet 容器将自行决定提供 HTML(正如您已经看到的)。
关于java - 如何自定义自定义 http 错误代码返回的默认 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26509881/