Xitrum学习笔记15 - Action过滤器
Before过滤器
Before过滤器在action执行之前执行。如果before过滤器响应返回了什么内容,在它之后的所有过滤器和action都不再运行
import xitrum.Action import xitrum.annotation.GET @GET("before_filter") class MyAction extends Action { beforeFilter { log.info("I run therefore I am") } // This method is run after the above filters def execute() { respondInlineView("Before filters should have been run, please check the log") } }
After过滤器
After过滤器在action运行之后运行,是不带参数的函数,返回值会被忽略
import xitrum.Action import xitrum.annotation.GET @GET("after_filter") class MyAction extends Action { afterFilter { log.info("Run at " + System.currentTimeMillis()) } def execute() { respondText("After filter should have been run, please check the log") } }
Around过滤器
import xitrum.Action import xitrum.annotation.GET @GET("around_filter") class MyAction extends Action { aroundFilter { action => val begin = System.currentTimeMillis() action() val end = System.currentTimeMillis() val dt = end - begin log.info(s"The action took $dt [ms]") } def execute() { respondText("Around filter should have been run, please check the log") } }
如果有多个around过滤器,它们会被嵌套使用。
过滤器的执行顺序
- Before过滤器先被执行,然后是around过滤器,最后是after过滤器
- 如果before过滤器中的一个返回false,其他的过滤器(包括around和after)将不再执行
- After过滤器会在至少一个around过滤器被执行后执行
- 如果一个around过滤器不调用action(),内嵌的around过滤器将不会执行
before1 -true-> before2 -true-> +--------------------+ --> after1 --> after2
| around1 (1 of 2) |
| around2 (1 of 2) |
| action |
| around2 (2 of 2) |
| around1 (2 of 2) |
+--------------------+