1. 程式人生 > >struts2中預設攔截器棧中的攔截器…

struts2中預設攔截器棧中的攔截器…


1:  com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor

     While you can configure exception mapping in your configuration file at any point, the configuration
     * will not have any effect if this interceptor is not in the interceptor stack for your actions.
     It is recommended that
     * you make this interceptor the first interceptor on the stack,
     ensuring that it has full access to catch any
     * exception, even those caused by other interceptors.
     這句話的意思是你可以配置異常在任何位置,只要這個攔截器沒有加入生效的攔截器棧中,該攔截器就不會生效;
     官方建議,將異常攔截器配置在攔截器的第一個位置,因為只有這樣才能更好的捕獲異常,甚至是
     其他攔截器發生的異常;
      @Override
        public String intercept(ActionInvocation invocation) throws Exception {
        String result;

        try {
            result = invocation.invoke();
        } catch (Exception e) {
            if (isLogEnabled()) {
            handleLogging(e);
            }
            List<ExceptionMappingConfig> exceptionMappings =
            invocation.getProxy().getConfig().getExceptionMappings();
            ExceptionMappingConfig mappingConfig =
            this.findMappingFromExceptions(exceptionMappings, e);
            if (mappingConfig != null && mappingConfig.getResult()!=null) {
            Map parameterMap = mappingConfig.getParams();
            // create a mutable HashMap since some interceptors will remove parameters, and parameterMap is immutable
            invocation.getInvocationContext().setParameters(new HashMap<String, Object>(parameterMap));
            result = mappingConfig.getResult();
            publishException(invocation, new ExceptionHolder(e));
            } else {
            throw e;
            }
        }

        return result;
        }
    這個攔截器的關鍵程式碼:
    這段程式碼的意思是,ActionInvocation呼叫棧中下一個的攔截器或者action物件(統稱為元素);
    對這個呼叫進行try catch 捕獲;
    如果呼叫這個方法不拋異常,直接將invoke方法的結果返回,回到ActionInvocation中繼續執行棧中的下一個元素
    (可能是攔截器,也有可能是action類);