我有一个grails 2.1.1应用程序,该应用程序运行良好,至少在我尝试在session
变量中设置user
的所有Controller
的过滤器以重定向到index.gsp
。..
我尝试什么,启动服务器时我无法重定向到"/index",也无法重定向到"/渲染"/索引 - 如果我删除过滤器并将其重定向到"/index",请从我的 AuthenticationController
上重定向到false参数上的"/索引",所有这些都像魅力一样...
所以,这是我到目前为止所拥有的:
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:重定向到任何控制器中的index.gsp升级到Grails 2.0:/index.gsp找不到Grails:部署WebLogic时的主要问题(及其解决方案)是什么?
但是我没有运气...
我正在使用Intellij Idea 11.1.4 Premium(评估)
开发编辑:我试图从session
类中的CC_12属性中获取User
对象,并被try/catch
块包围,现在面临显然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
字段来轻松执行此操作。如果没有任何控制器将用户转介给网站,则应是null
或""
(空字符串)。
另外,我在应用程序中没有使用任何数据库进行身份验证,因为所有这些ISSU都由API支持。因此,我创建了一个UserService.groovy
类,该类充当SessionScopedBean
,然后将所有用户相关的Infos存储在此类中。
因此,您的过滤器定义看起来像:
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
类来这样做。只需将您的/
(root)索引映射到您想要的页面:
class UrlMappings {
static mappings = {
"/"(controller:'mycontroller',action:'myaction') // change it to your liking
"/$controller/$action?/$id?" {
constraints {
// apply constraints here
}
}
"500"(view:'/error')
}
}
我认为您的过滤器语法可能不正确 - 尝试
Class AuthenticationFilters {
def filters = { // <--- added this
all(controller:'*', action'*') {
before = {
def user = (User) session.getValue("user")
if(user == null || !user.loginState) {
redirect(controller: 'authentication', action: 'index')
return false
}
}
}
} // <-- added
}