`
linxuexin
  • 浏览: 26248 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

Struts2拦截器之AliasInterceptor

阅读更多

这个拦截器在xwork的jar包里,它的作用是给参数起一个别名,可用于在action链中以不同的名字共享同一个参数,也可用于把http请求参数以不同的名字映射到action里。

拦截器有一个参数:aliasesKey,可通过在struts.xml中定义该拦截器时指定其值,默认值是aliases,表示一个别名的map。

下面以实现在action链中以不同的名字共享同一个参数为例:

struts.xml
<package name="test" namespace="/test">  
    <action name="aliasTestFrom" class="test.AliasInterceptorTestFromAction">  
        <result type="chain">aliasTestTo</result>  
    </action>  
           
    <action name="aliasTestTo" class="test.AliasInterceptorTestToAction">  
        <param name="aliases">#{'someList' : 'otherList'}</param>  
        <result>/test/alias_result.jsp</result>  
    </action>  
</package>  
param标签的name属性值应该和拦截器参数aliasesKey的值一样,这样拦截器才知道你是否指定了action的别名map。这个map应该象#{原参数名1 : 别名1, 原参数名2 : 别名2}这样的形式,这是一个定义map的OGNL表达式。

该拦截器已经包含在defaultStack中,因此上面没有显示的指定。

相应的,在本例中,test.AliasInterceptorTestFromAction里有一个字段someList:

AliasInterceptorTestFromAction.java
private List someList;   
       
public List getSomeList() {   
    return someList;   
}   
  
public void setSomeList(List someList) {   
    this.someList = someList;   
}  
test.AliasInterceptorTestToAction里有一个字段otherList:

AliasInterceptorTestToAction.java
private List otherList;   
       
public List getOtherList() {   
    return otherList;   
}   
  
public void setOtherList(List otherList) {   
    this.otherList = otherList;   
}  
注意:在AliasInterceptorTestToAction中不能有一个叫someList的字段,如果有的话,otherList最终的值将是AliasInterceptorTestToAction中的someList,而非AliasInterceptorTestFromAction的值。因为该拦截器的实现是在action的值栈里找到原参数名后设置给别名,如果两个action都有someList,而AliasInterceptorTestToAction位于栈顶,它的someList将被赋给otherList,这并不是我们所期望的结果。

someList也可以来自于http请求参数,因为拦截器如果在action的值栈里没有找到someList,还会在http请求参数里找。

分享到:
评论
1 楼 lykm02 2012-04-12  
这个 interceptor 只在 action chain中有作用,也太弱了。

相关推荐

Global site tag (gtag.js) - Google Analytics