您的位置:首页 > 编程语言 > Java开发

Struts2拦截器 —— prepare拦截器

2013-11-06 14:47 477 查看
实现类
com.opensymphony.xwork2.interceptor.PrepareInterceptor
 
作用
为实现了com.opensymphony.xwork2.Preparable接口的action调用相关方法。
 
两个参数

参数名
值类型
默认值
描述
alwaysInvokePrepare
boolean
true
如果其值为true则调用接口定义的prepare方法。
firstCallPrepareDo
boolean
false
如果值为true,则调用prepareDoXXX方法。
否则调用prepareXXX方法(XXX为action对应的方法)。
 
关键源码

    public
String doIntercept(ActionInvocation invocation) throws Exception {

        Object action = invocation.getAction();

        if (action
instanceof Preparable) {

            try {

                String[] prefixes;

                if (firstCallPrepareDo) {

                    prefixes = new String[] {ALT_PREPARE_PREFIX, PREPARE_PREFIX};

                } else {

                    prefixes = new String[] {PREPARE_PREFIX, ALT_PREPARE_PREFIX};

                }

                PrefixMethodInvocationUtil.invokePrefixMethod(invocation, prefixes);

            }

            catch (InvocationTargetException e) {

                /*
                 * The invoked method threw an exception and reflection wrapped it
                 * in an InvocationTargetException.
                 * If possible re-throw the original exception so that normal
                 * exception handling will take place.
                 */

                Throwable cause = e.getCause();

                if (cause
instanceof Exception) {

                    throw (Exception) cause;

                } else if(cause
instanceof Error) {

                    throw (Error) cause;

                } else {

                    /*
                     * The cause is not an Exception or Error (must be Throwable) so
                     * just re-throw the wrapped exception.
                     */

                    throw e;

                }

            }

            if (alwaysInvokePrepare) {

                ((Preparable) action).prepare();

            }

        }

        return invocation.invoke();

    }
 
执行顺序
在struts2中,如果Action实现了Prepare接口:
prepare<方法名>()
 --> prepare() --> validate<方法名>方法
--> execute方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息