在web.xml中定义的页面总是返回HTTP状态200

我有一个运行在Jboss 7(EAP 6.4)上的EE6 JAX-RS应用程序,并通过ExceptionMapper的实现在内部处理其大部分异常和错误。

但是,有些情况下(最明显的是当HTTP Basic Auth失败时),因为错误发生在应用程序被调用之前,因此客户端获取服务器的默认错误页面(JBWEB bla bla,带有丑陋紫色的HTML )。

现在为了捕获这些“外部”错误,我在web.xml添加了<error-page>定义,如下所示:

<error-page>
    <location>/error.json</location>
</error-page>
<error-page>
    <error-code>401</error-code>
    <location>/error401.json</location>
</error-page>

该位置工作正常,我几乎得到我想要的响应, 但HTTP状态代码始终为200。

至少可以说,这很烦人。 如何获取错误页面以返回其正确的错误代码?


最后我写了一个小型web服务(而不是静态页面),它会给我一个JSON响应和正确的HTTP状态代码以及相关的标题:

<error-page>
    <error-code>401</error-code>
    <location>/error/401</location>
</error-page>

哪个呼叫该服务

@Path("/error")
public class ErrorService {

    private static final Map<Integer, String> statusMsg;
    static
    {
        statusMsg = new HashMap<Integer, String>();
        statusMsg.put(401, "Resource requires authentication");
        statusMsg.put(403, "Access denied");
        statusMsg.put(404, "Resource not found");
        statusMsg.put(500, "Internal server error");
    }

    @GET
    @Path("{httpStatus}")
    public Response error(@PathParam("httpStatus") Integer httpStatus) {

        String msg = statusMsg.get(httpStatus);
        if (msg == null)
            msg = "Unexpected error";

        throw new MyWebApplicationException.Builder()
            .status(httpStatus)
            .addError(msg)
            .build();
    }

}

我有一个异常类MyWebApplicationException ,它具有自己的构建器模式,我以前曾经使用jax-rs ExceptionMapper将各种应用程序错误格式化为JSON。

所以现在我只是通过相同的渠道来处理外部捕获的错误(如发生在JAX-RS之外的401)。


错误页面机制的意图是向最终用户展示人类可读的东西。 如果它返回一些200以外的代码,它将以浏览器的常用方式处理(浏览器的标准错误消息)。

链接地址: http://www.djcxy.com/p/45585.html

上一篇: page> defined in web.xml always comes back with HTTP status 200

下一篇: 415 error when sending json data back to java rest service using AJAX