gpt4 book ai didi

java - web.xml 中的条件错误页面/使用 Jersey 跳过错误页面

转载 作者:行者123 更新时间:2023-12-03 22:00:30 25 4
gpt4 key购买 nike

我有一个包含 JSF 和 Jersey 的 Web 应用程序:

/contextpath/rest/whatever -> Jersey
/contextpath/everythingelse -> JSF

如果JSF出现错误,即500内部服务器错误,由于web.xml中的config,会显示错误页面
...
<error-page>
<error-code>403</error-code>
<location>forbidden.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/path/to/errorhandler.jsp</location>
</error-page>

这在“JSF-land”中按预期工作。但是,如果 Jersey 资源抛出异常:
  • ExceptionMapper (Jersey) 处理异常,
  • 发送错误响应(例如 403 禁止)
  • 由于它是在 web.xml 中定义的,所以将提供 forbidden.jsp 页面

  • 这具有调用 forbidden.jsp 的不良副作用,并将 HTML 返回给请求 application/json 的客户端。我的第一个虽然是有条件地编写错误页面语句,因此它们只会启动非剩余资源,但这似乎是不可能的。

    其他建议?

    最佳答案

    所以,如果有人在 8 年后仍然面临这个问题(是的,我也不为此感到自豪......)这就是我修复它的方式:
    向 web.xml 添加了一个针对 servlet 的错误页面:

    <error-page>
    <error-code>403</error-code>
    <location>/403Handler</location>
    </error-page>
    创建了 403Handler servlet:
    @WebServlet("/403Handler")
    public class 403Handler extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    processError(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    processError(request, response);
    }

    private void processError(HttpServletRequest request, HttpServletResponse response) {
    Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
    if (statusCode != 403) {
    return;
    }

    String originalUrl = (String) request.getAttribute("javax.servlet.error.request_uri");
    if (StringUtils.startsWith(originalUrl, "contextpath/rest")) {
    return;
    }

    try {
    request.getRequestDispatcher("/path/to/errorhandler.jsp").forward(request, response);
    } catch (ServletException | IOException e) {
    log.error("failed to foward to error handler", e);
    }
    }

    关于java - web.xml 中的条件错误页面/使用 Jersey 跳过错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13193920/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com