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

struts2拦截器简介

2008-11-06 13:18 337 查看
 

拦截器介绍<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

拦截器-Exception

<interceptor name="exception" class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"/>

配置Exception,如果出现什么样的异常就跳转到对应的页面。

在action执行之后,抛出异常才会被调用的。

拦截器alias

在action执行之前执行
The aim of this Interceptor is to alias a named parameter to a different named parameter. By acting as the glue between actions sharing similiar parameters (but with different names), it can help greatly with action chaining.

 

主要用在chain的action,如果从一个action直接跳转到另外一个action,可能需要传递参数值,而参数的名称是不一样的,这个时候alias拦截器就起作用了。

拦截器-ServletConfig

在action执行之前执行
 

An interceptor which sets action properties based on the interfaces an action implements. For example, if the action implements
ParameterAware
then the action context's parameter map will be set on it.

配置了这个拦截器后,action可以实现某些接口,就可以自动获取到某些对象,例如request和response对象。

详细的例子:com.work.core.action.OurActionSupport

拦截器-prepare

在action执行之前执行
必须实现Preparable接口,com.opensymphony.xwork2.Preparable
<interceptor name="prepare" class="com.opensymphony.xwork2.interceptor.PrepareInterceptor"/>

 

可以通过setAlwaysInvokePrepare方法,来决定prepare()是否要被执行。

和validate方法一样,你可以在action中设定prepareList()方法,那么这个方法就会被首先执行,然后在执行prepare方法。(prepareDoList也可以)。

先执行prepareList如果这个找不到就寻找prepareDoList方法,如果都找不到就不执行。

需要测试。
(注意:需要使用呢params prepare params 拦截器的配置方式)
Prepare方法,当前action中的任何方法执行都会执行到他;
import com.opensymphony.xwork2.Preparable;
    public void prepare() throws Exception {

       if(log.isInfoEnabled())

           log.info("执行prepare()方法了");    

    }

    /**

     * 测试失败!

     * @throws Exception

     */

    public void prepareLoadForEdit() throws Exception {

       if(log.isInfoEnabled())

           log.info("执行prepareLoadForEdit()方法了");

       try {

           if (labid == null) {

              //lab = null;

              log.debug("labid==null");

           } else {

              lab = labServiceDao.loadForEditById(labid);

              log.debug("lab="+lab);

           }

       } catch (DataAccessException e) {

           if (log.isErrorEnabled()) {

              log.error("根据labid"+labid+"查询出错。", e);

           }

       }

      

    }  

拦截器-i18n

在action执行之前执行
 

<interceptor name="i18n" class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/>

 

实现国际化的功能。
 

拦截器-chain

在action执行之前执行
如果action实现了接口com.opensymphony.xwork2.Unchainable,那么对应的属性将不再拷贝。

An interceptor that copies all the properties of every object in the value stack to the currently executing object, except for any object that implements Unchainable. A collection of optional includes and excludes may be provided to control how and which parameters are copied. Only includes or excludes may be specified. Specifying both results in undefined behavior. See the javadocs for OgnlUtil.copy(Object, Object, java.util.Map, java.util.Collection, java.util.Collection) for more information.

It is important to remember that this interceptor does nothing if there are no objects already on the stack. This means two things: One, you can safely apply it to all your actions without any worry of adverse affects. Two, it is up to you to ensure an object exists in the stack prior to invoking this action. The most typical way this is done is through the use of the chain result type, which combines with this interceptor to make up the action chaining feature.

 

拦截器- scopedModelDriven

在action执行之前执行
你的action实现com.opensymphony.xwork2.interceptor. ScopedModelDriven接口;

如果一个Action实现了ScopedModelDriven,则这个拦截器会从相应的Scope中取出model调用Action的setModel方法将其放入Action内部。

 

拦截器- modelDriven

在action执行之前执行
实现ModelDriven接口
Watches for ModelDriven actions and adds the action's model on to the value stack.

Note: The ModelDrivenInterceptor must come before the both StaticParametersInterceptor and ParametersInterceptor if you want the parameters to be applied to the model.

 

拦截器- fileUpload

上传文件的代码,在action执行之前执行,清除临时文件在action之后执行。
 

<interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>

 

 

拦截器- checkbox(还需要测试,不是很明白)

在action执行之前执行
org.apache.struts2.interceptor.CheckboxInterceptor

 

如果使用了checkbox标签,才使用这个吧?
 

这个拦截器的功能比较奇怪啊,看了源代码,也不明白为什么要将checkbox没有选中的设置为false。
    public String intercept(ActionInvocation ai) throws Exception {

        Map parameters = ai.getInvocationContext().getParameters();

        Map<String, String> newParams = new HashMap<String, String>();

        Set<String> keys = parameters.keySet();

        for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) {

            String key = iterator.next();

 

            if (key.startsWith("__checkbox_")) {

                String name = key.substring("__checkbox_".length());

 

                iterator.remove();

 

                // is this checkbox checked/submitted?

                if (!parameters.containsKey(name)) {

                    // if not, let's be sure to default the value to false

                    newParams.put(name, uncheckedValue);

                }

            }

        }

 

        parameters.putAll(newParams);

 

        return ai.invoke();

}

 

设置checkbox标签不被选中的时候的默认值

<interceptor-ref name="checkbox">
          <param name="uncheckedValue">0</param>
       </interceptor-ref>

拦截器- staticParams

在action执行之前执行
 

<interceptor name="staticParams" class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/>

This interceptor populates the action with the static parameters defined in the action configuration. If the action implements
Parameterizable
, a map of the static parameters will be also be passed directly to the action.

 

在struts的xml配置文件中配置的参数

拦截器-params

在action执行之前执行
 

<interceptor name="params"

class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>

将所有的参数值放入到stack中去。(Ognl)
ParameterNameAware接口
com.opensymphony.xwork2.interceptor.ParameteraNameAware

实现了此接口,可以设定允许哪些action的属性的值被放入stack中去。

 

拦截器-conversionError

在action执行之前执行
转换器
<interceptor name="conversionError" class="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor"/>

将错误从ActionContext中添加到Action的属性字段中

 

拦截器- validation(xml自动校验配置文件)

在action执行之前执行
使用action-validation.xml文件中定义的内容校验提交的数据。

 

拦截器-workflow(执行action中的validate方法)

在action执行之前执行
 

调用Action的validate方法,一旦有错误返回,重新定位到INPUT画面

<interceptor name="workflow" class="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/>

和prepare拦截器类似啊
顺序查找并执行下面的方法。
ValidateSave  validateDoSave  validate 
 

===拦截器必须是线程安全的==========================

拦截器-cookie

将cookie的值,放到valuestack中去,
你也可以实现接口CookiesAware,在程序中编程设置。

 

拦截器- createSession

org.apache.struts2.interceptor.CreateSessionInterceptor

 

This interceptor creates the HttpSession.

This is particular usefull when using the <@s.token> tag in freemarker templates. The tag do require that a HttpSession is already created since freemarker commits the response to the client immediately.

拦截器-其他

Debugging Interceptor
debugging
提供不同的调试用的页面来展现内部的数据状况。
Execute and Wait Interceptor
execAndWait
在后台执行Action,同时将用户带到一个中间的等待页面。
Message Store Interceptor
store
存储或者访问实现ValidationAware接口的Action类出现的消息,错误,字段错误等。
Scope Interceptor
scope
将Action状态存入session和application的简单方法。
Roles Interceptor
roles
确定用户是否具有JAAS指定的Role,否则不予执行。
Token Interceptor
token
通过Token来避免双击
Token Session Interceptor
tokenSession
和Token Interceptor一样,不过双击的时候把请求的数据存储在Session中
Parameter Filter Interceptor
N/A
从参数列表中删除不必要的参数
Profiling Interceptor
profiling
通过参数激活profile
 

 

在拦截器中获取action的属性值

// 找到对应的临时文件的路径

       String tempFilePath = (String) invocation.getStack().findValue(

              "tempFilePath");

 

给拦截器栈中的某个拦截器配置参数的方法

<!DOCTYPE xwork PUBLIC

        "-//OpenSymphony Group//XWork <?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />1.1.1//EN"

        "http://www.opensymphony.com/xwork/xwork-1.1.1.dtd"

        >

 

<xwork>

    <include file="xwork-test-beans.xml" />

    <package name="default">

        <interceptors>

            <interceptor name="timer" class="com.opensymphony.xwork2.interceptor.TimerInterceptor"/>

            <interceptor name="test" class="com.opensymphony.xwork2.mock.MockInterceptor">

                <param name="foo">fooDefault</param>

            </interceptor>

 

            <interceptor-stack name="defaultStack">

                <interceptor-ref name="timer"/>

                <interceptor-ref name="test"/>

            </interceptor-stack>

        </interceptors>

 

        <default-interceptor-ref name="defaultStack" />

 

        <action name="TestInterceptorParam" class="com.opensymphony.xwork2.SimpleAction">

            <interceptor-ref name="defaultStack">

                <param name="test.expectedFoo">expectedFooValue</param>

            </interceptor-ref>

        </action>

 

        <action name="TestInterceptorParamOverride" class="com.opensymphony.xwork2.SimpleAction">

            <interceptor-ref name="defaultStack">

                <param name="test.foo">foo123</param>

                <param name="test.expectedFoo">expectedFooValue2</param>

            </interceptor-ref>

           defaultStack中有个拦截器的名称为test,test拦截器中有配置参数的get和set方法。

        </action>

    </package>

 

</xwork>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息