有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

web中的java条件错误页。xml/skip errorpage与Jersey

我有一个同时使用JSF和Jersey的Web应用程序:

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

如果JSF、ie 500内部服务器错误中出现错误,则会由于web中的配置而显示错误页面。xml

...
<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陆地”中,这项功能可以正常工作。但是,如果Jersey资源引发异常:

  1. ExceptionMapper(Jersey)处理异常,并
  2. 发送错误响应(例如403禁止)
  3. 因为它是在web中定义的。xml,这是被禁止的。将提供jsp页面

这会产生调用“禁止”的不良副作用。jsp并将HTML返回给请求application/json的客户机。我的第一个想法是有条件地编写错误页语句,这样它们只会占用非rest资源,但这似乎是不可能的

其他建议


共 (1) 个答案

  1. # 1 楼答案

    所以,如果有人在8年后仍然面临这个问题(是的,我也不为此感到骄傲…)我就是这样修复的:

    已将错误页添加到web。以servlet为目标的xml:

    <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);
        }
    }