发生异常时的 JSF 响应代码
JSF response code when exception ocurrs
在我的 JSF 应用程序中,我在用户未登录时抛出 java.lang.SecurityException
。在 web.xml
中,当出现 SecurityException
时,我重定向到 login.jsf
。
现在我的问题是,当我查看服务器响应时,它是 500 - Internal Server Error
。我能以某种方式抛出 SecurityException
并说它应该是 401
吗?
谢谢
当异常一直冒泡到 servlet 容器并作为未处理的异常到达时,根据定义,它始终是 HTTP 500 错误。你不能改变那部分。
然而,您可以通过在某处捕获和抑制特定异常然后显式调用 HttpServletResponse#sendError()
来控制它,传递所需的 4xx/5xx 状态代码。
对于同步请求,最明智的地方是 servlet filter。
try {
chain.doFilter(request, response);
}
catch (SecurityException e) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
}
注意:如果它不是 RuntimeException
,请捕获 ServletException
并检查它的 getRootCause()
。另见 a.o。 How does server prioritize which type of web.xml error page to use?
对于异步 (Ajax) 请求,您确实需要一个额外的自定义异常处理程序。另见 a.o。 Exception handling in JSF ajax requests。这当然只有在您通过 Ajax.
执行登录时才有意义
或者,如果您已经有一个执行授权的 servlet 过滤器,那么只需执行 sendError()
而不是抛出 SecurityException
。如果您的授权过滤器看起来像 How implement a login filter in JSF? 中的那个,那么只需将底部的重定向替换为:
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
无论哪种方式,它最终都会出现在与 401 的 <error-code>
关联的错误页面中。
<error-page>
<error-code>401</error-code>
<location>/WEB-INF/errorpages/unauthorized.xhtml</location>
</error-page>
在我的 JSF 应用程序中,我在用户未登录时抛出 java.lang.SecurityException
。在 web.xml
中,当出现 SecurityException
时,我重定向到 login.jsf
。
现在我的问题是,当我查看服务器响应时,它是 500 - Internal Server Error
。我能以某种方式抛出 SecurityException
并说它应该是 401
吗?
谢谢
当异常一直冒泡到 servlet 容器并作为未处理的异常到达时,根据定义,它始终是 HTTP 500 错误。你不能改变那部分。
然而,您可以通过在某处捕获和抑制特定异常然后显式调用 HttpServletResponse#sendError()
来控制它,传递所需的 4xx/5xx 状态代码。
对于同步请求,最明智的地方是 servlet filter。
try {
chain.doFilter(request, response);
}
catch (SecurityException e) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
}
注意:如果它不是 RuntimeException
,请捕获 ServletException
并检查它的 getRootCause()
。另见 a.o。 How does server prioritize which type of web.xml error page to use?
对于异步 (Ajax) 请求,您确实需要一个额外的自定义异常处理程序。另见 a.o。 Exception handling in JSF ajax requests。这当然只有在您通过 Ajax.
执行登录时才有意义或者,如果您已经有一个执行授权的 servlet 过滤器,那么只需执行 sendError()
而不是抛出 SecurityException
。如果您的授权过滤器看起来像 How implement a login filter in JSF? 中的那个,那么只需将底部的重定向替换为:
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
无论哪种方式,它最终都会出现在与 401 的 <error-code>
关联的错误页面中。
<error-page>
<error-code>401</error-code>
<location>/WEB-INF/errorpages/unauthorized.xhtml</location>
</error-page>