在JSF應(yīng)用中捕捉managed-bean構(gòu)造方法
有時候需要在managed-bean構(gòu)造方法里執(zhí)行一些邏輯代碼,這時如果拋出了異常,該如何捕捉呢?
JSF的事件被執(zhí)行時,如果在事件處理方法中拋出了Exception,我們可以通過JSF提供的ActionListener機(jī)制catch到拋出的Exception,然后根據(jù)Exception類型執(zhí)行不同的錯誤處理。
但有時候需要在managed-bean構(gòu)造方法里執(zhí)行一些邏輯代碼,這時如果拋出了異常,該如何捕捉呢?
你可能會想到在Filter里加以捕捉處理,但不幸的是,你在Filter里只能捕捉到經(jīng)過被加工了的Exception:ServletException,而且你也沒辦法將其還原成最初被拋出的Exception。
要達(dá)到這個目的,我們可以利用JSF框架提供的variable-resolver切入點。因為JSF的managed-bean的instance,就是由variable-resolver所定義類所生成的。
所以我們可以借助JSF提供的機(jī)制,注冊我們自己的variable-resolver類,從而就可以捕捉到managed-bean構(gòu)造方法執(zhí)行時拋出的異常了。
具體方法為:
自定義一個VariableResolverImpl類,該類需要實現(xiàn)虛類javax.faces.el.VariableResolver,為了簡便起見,我們可以根據(jù)情況,重載所使用的JSF實現(xiàn)里的相關(guān)類就可以了,比如MyFaces的情況下,重載 org.apache.myfaces.el.VariableResolverImpl. resolveVariable方法就可以了。
代碼如下:
- package mypackage;
- import javax.faces.context.FacesContext;
- import javax.servlet.http.HttpServletRequest;
- public class VariableResolverImpl extends
- org.apache.myfaces.el.VariableResolverImpl {
- private static final String ERROR_FLAG = "error";
- private static final String EXCEPTION_TYPE = "exception";
- @Override
- public Object resolveVariable(FacesContext facesContext, String name) {
- try {
- return super.resolveVariable(facesContext, name);
- } catch (Throwable e) {
- HttpServletRequest request = (HttpServletRequest)facesContext. getExternalContext().getRequest();
- request.setAttribute(ERROR_FLAG, Boolean.TRUE);
- request.setAttribute(EXCEPTION_TYPE, e);
- throw new RuntimeException(e);
- }
- }
- }
在faces-config.xml里注冊剛才實現(xiàn)的類,讓JSF使用我們提供的類解析變量
- <faces-config>
- <!-- Application Config -->
- <application>
- <variable-resolver>mypackage.VariableResolverImpl</variable-resolver>
- <!-- other configuration here -->
- </application>
- <!-- other configuration here -->
- </faces-config>
在其他地方處理異常,比如Filter里
- public class AppFilter implements Filter {
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
- ServletException {
- try {
- chain.doFilter(request, response);
- } catch (ServletException e) {
- Boolean error = (Boolean)request.getAttribute("error");
- if (Boolean.TRUE.equals(error)) {
- Throwable te = (Throwable)request.getAttribute("exception");
- if (te instanceof AppException) {
- //TODO do business here
- } else {
- //TODO do business here
- }
- } else {
- //TODO do business here
- }
- }
- }
【編輯推薦】