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
  }
}

猜你喜欢

转载自blog.csdn.net/chs007chs/article/details/80322066