你好,游客 登录 注册 搜索
背景:
阅读新闻

Commons Chain使用

[日期:2012-12-23] 来源:Linux社区  作者:devotion987 [字体:大 中 小]

4. Filter的使用。Filter是一种特殊的Command,它除了execute方法会被执行之外,同时还会在Chain执行完毕之后(不论是正常结束还是异常结束)执行postprocess。因此,可以将它和Servlet中的Filter做类比:execute相当于处理前操作(相对下一个Command来说),postprocess相当于处理后操作。Filter的使用以及配置和Command完全一样,为了在Command1之前添加一个Filter:

定义Filter

public class Filter1 implements Filter {

public boolean postprocess(Context arg0, Exception arg1) {

System.out.println("Filter1 is after done!");

return false;

}

public boolean execute(Context arg0) throws Exception {

 System.out.println("Filter1 is done!");

return false;

}

}


修改配置文件,在上述的配置文件中的command1之前添加:

  <command id="filter1" className= "chain.Filter1"/>

Filter还有一个常用的用法:对于异常的过滤。当Command抛出异常时,最终会返回到最开始的调用处。有时期望不抛出这些异常,而在内部消化掉,那么就可以利用Filter。因为Commons Chain确保会调用已经执行了execute方法的Filter的postprocess方法,即使在出现异常时也是如此。因此,对应的postprocess方法可以写为:

public boolean postprocess(Context arg0, Exception arg1) {

//返回true,表示非空异常已被处理,无需再抛出。

//否则,异常会被抛出

if( null!= arg1) return true;

else return false;

}

5. 对于复杂的Chain,可能需要使用内嵌的Chain,内嵌Chain可以类比一个子过程。此时,可以使用LookupCommand。以例1为例,假设其中的command2需要扩展成为一个子过程,那么配置文件修改如下:

<?xml version="1.0" encoding="UTF-8"?>

<catalog>

<chain name="CommandChain">

<command id="command1" className= "chain.Command1"/>

<command id="filter1" className= "chain.Filter1"/>

<command

      className="org.apache.commons.chain.generic.LookupCommand"

name="chain_command3"

optional="true"/>

<command id="command2" className= "chain.Command2"/>

</chain>

<chain name="chain_command3">

<command id="command3" className= "chain.Command3"/>

</chain>

</catalog>

  其中,optional如果设为true,那么如果没有找到对应的类时,程序不会抛出异常。此时,仿佛命令不存在一样。如果为false,那么在找不到对应的类时,会抛出异常。

linux
相关资讯       Commons Chain 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款