gpt4 book ai didi

Grails 2.1.1 : Redirect to/index. gsp 无法使用定义的过滤器

转载 作者:行者123 更新时间:2023-12-02 13:49:17 25 4
gpt4 key购买 nike

我有一个运行良好的 Grails 2.1.1 应用程序,至少在我尝试为所有 Controller 定义一个过滤器以重定向到 index.gsp 之前,如果 user 未在 session 变量中设置...

无论我尝试什么,我都无法重定向到“/index”,也无法在启动服务器时呈现“/index”——如果我删除过滤器并从我的 AuthenticationController 重定向到“/index” 在错误的参数上,一切都像魅力...

所以,这是我目前所拥有的:

class AuthenticationFilters {
all(controller:'*', action'*') {
before = {
def user = (User) session.getValue("user")
if(user == null || !user.loginState) {
redirect(controller: 'authentication', action: 'index')
return false
}
}
}
}

class AuthenticationController {
def authenticationService

def index = {
render(view: '/index')
}

def login(LoginCommand cmd) {
if(cmd.hasErrors()) {
redirect(action: index)
return
}
}
....
}

现在,如果我注释掉 all 过滤器定义,一切正常。我得到了启动时显示的页面 (index.gsp),如果 LoginCommand 有错误,我将被重定向到 index.gsp 页面,没有任何问题。如果我现在在 all 过滤器定义中发表评论,我会得到一个 404

我试过: Grails: Redirect to index.gsp that is not in any controller Upgrade to Grails 2.0: /index.gsp not found Grails: what are the main issues (and his solutions) when deploying in weblogic?

但我没有任何运气......

我正在使用 Intellij IDEA 11.1.4 Premium(评估版)进行开发


编辑:我试图从我的 AuthenticationFilters 类中的 session 属性获取 User 对象,包围通过 try/catch block ,现在面临的问题是 session 属性显然不可用?为什么?

try {
def user = (User) session.getValue("user")
if((user == null || !user.loginState)) {
...
}
} catch(Exception e) {
println("... couldn't get user from session! ${e.getMessage()}")
}

控制台输出:

... couldn't get user from session! No such property: session for class: grailstest001.AuthenticationFilters

对此有什么建议吗?

最佳答案

所以,只是在这里添加我的经验来关闭这个已解决的问题并供其他用户进一步使用:

要检查用户是否是第一次进入该页面,您可以通过检查 controllerName 字段轻松地做到这一点。如果用户未被任何 Controller 引用到站点,则它应该是 null""(空字符串)。

此外,我没有在我的应用程序中使用任何数据库进行身份验证,因为所有这些问题都由 API 支持。所以我创建了一个 UserService.groovy 类,它作为一个 SessionScopedBean,我将所有与用户相关的信息存储在这个类中。

因此,您的过滤器定义可能如下所示:

class MyFilters {
def filters = {
before = {
if(!controllerName || controllerName.equals("")) {
redirect(controller:'home',action:'index')
}
if(!applicationContext.userService?.getUser() || !applicationContext.userService?.getUser.isLoggedIn) {
redirect(controller:'auth',action:'login')
}
}
}
}

否则,如果您不想重定向从 Filters.groovy 类中“刚”进入您的页面的用户,您可以使用 UrlMappings.groovy 类这样做。只需将您的 /(根)索引映射到您想要的页面:

class UrlMappings {
static mappings = {
"/"(controller:'mycontroller',action:'myaction') // change it to your liking
"/$controller/$action?/$id?" {
constraints {
// apply constraints here
}
}
"500"(view:'/error')
}
}

关于Grails 2.1.1 : Redirect to/index. gsp 无法使用定义的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13272599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com