加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Grails的beforeInterceptor拦截器

发布时间:2020-12-14 17:03:34 所属栏目:大数据 来源:网络整理
导读:可选的 beforeInterceptor 属性可以在action开始执行之前中断它的运行。 ? 简单的跟踪拦截器: def beforeInterceptor = { println "Tracing action ${actionUri}" } 一个安全验证拦截器保证用户已登录: ? def beforeInterceptor = [action: this .auth,exc

可选的beforeInterceptor属性可以在action开始执行之前中断它的运行。

?

简单的跟踪拦截器:

def beforeInterceptor = {
       println "Tracing action ${actionUri}"
}

一个安全验证拦截器保证用户已登录:

?

def beforeInterceptor = [action:this.&auth,except:'login']
// defined as a regular method so its private
def auth() {
     if(!session.user) {
            redirect(action:'login')
            return false
     }
}
def login = {
     // display login page
}

beforeInterceptor拦截器可以在action开始之前中断它的运行,如果拦截器返回false则该action不会继续执行了。可以为controller中所有的action都加上这种拦截器,如下:

?

def beforeInterceptor = {
       println "Tracing action ${actionUri}"
}

上面的声明需要放在controller的定义中,它会在所有action运行前执行,但不会影响action的处理流程,一个常见的用法就是认证:

?

def beforeInterceptor = [action:this.&auth,except:'login']
// defined as a regular method so its private
def auth() {
     if(!session.user) {
            redirect(action:'login')
            return false
     }
}
def login = {
     // display login page
}

上面的代码定一个叫'auth'的方法,一个不会成为暴漏在外面的action的方法(就是说它是私有的)。'beforeInterceptor'属性为所有action(除了login action)定义了一个拦截器,拦截器会去执行'auth'方法,有了Groovy的方法指针语法。在这个方法中,先判断当前用户是否被设置了session,若没有的话,则会重定向到login action并返回false,这样,被中断的action的其他代码就不会被执行。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读