Grails - Interceptors

在Grails 3.0之前,Grails有Filter概念,3.0之后仍可使用,但并不推荐。

定义Interceptors

默认情部况下,Interceptors会拦截同名的controller请求,如果我们有一个interceptor称为BookInterceptor,那么所有请求BookController的请求都会触发这个interceptor。

一个Interceptor需要实现接口Interceptor,它有三个方法:

 

/**
 * Executed before a matched action
 *
 * @return Whether the action should continue and execute
 */
boolean before() { true }

/**
 * Executed after the action executes but prior to view rendering
 *
 * @return True if view rendering should continue, false otherwise
 */
boolean after() { true }

/**
 * Executed after view rendering completes
 */
void afterView() {}

before方法在请求执行之前调用,如果返回false,则取消当前调用。after方法,如果返回false,那么就会取消渲染view,同时也可以通过view和model属性修改view或者model。

boolean after() {
  model.foo = "bar" // add a new model attribute called 'foo'
  view = 'alternate' // render a different view called 'alternate'
  true
}

afterview方法是在view渲染成功之后调用。

拦截指定Request

通过match方法或者matchAll方法可以配置拦截的Request。

 

class AuthInterceptor {
  AuthInterceptor() {
    matchAll()
    .excludes(controller:"login")
  }

  boolean before() {
    // perform authentication
  }
}
class LoggingInterceptor {
  LoggingInterceptor() {
    match(controller:"book", action:"show") // using strings
    match(controller: ~/(author|publisher)/) // using regex
  }

  boolean before() {
    ...
  }
}

在Interceptor中可以使用多个matcher,它们会以定义的顺序执行。

指定Interceptor执行的顺序

通过order属性可以定义Interceptor执行的顺序。

 

class AuthInterceptor {

  int order = HIGHEST_PRECEDENCE

  ...
}

order默认值是0,值越小的越先执行,HIGHEST_PRECEDENCE--LOWEST_PRECEDENCE之间。

为了得到interceptor的执行顺序,可以在logback.groovy中添加:

 

logger 'grails.artefact.Interceptor', DEBUG, ['STDOUT'], false

也可以在grails-app/conf/application.yml中修改interceptor的order

 

beans:
  authInterceptor:
    order: 50

或者通过grails-app/conf/application.groovy

 

beans {
  authInterceptor {
    order = 50
  }
}

最后欢迎大家访问我的个人网站:1024s​​​​​​​

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值