0

我有一个 gsp 文件,它调用这样的方法:

<g:link id="${child.id}" action="callChildProfile" controller="profile">${child.firstname}</g:link>

调用此方法

    def callChildProfile(Long id){

           childInstance = Child.get(id)
           System.out.println(childInstance.firstname + "  child instance")
           redirect(action:  "index")

   }

此方法将一个子实例设置为一个称为子实例的公共变量,但是当重定向发生时,该变量会被重置。我重定向的原因是因为我想从这个控制器加载索引页面。

索引如下所示:

        def index() {
        def messages = currentUserTimeline()
        [profileMessages: messages]
         System.out.println(childInstance + " child here")
        [childInstance : childInstance]
    } 
4

2 回答 2

2

默认情况下,控制器是原型范围的,这意味着 used 的实例在调用的请求和ProfileController调用的请求之间是不同的。因此,对象级变量在请求之间将不可用。callChildProfileindexchildInstance

Child在调用中使用实例,index请查看方法:

callChildProfile(Long id){
    // do usual stuff
    chain(action:"index", model:[childInstance:childInstance])
}

def index() {
    // do other stuff
    [otherModelVar:"Some string"]
}

Mapindex模型返回时,链调用将自动添加,因此您的childInstancefromcallChildProfile将可用于 gsp。

于 2012-08-29T21:28:36.073 回答
1

控制器方法(动作)中的变量具有本地范围,因此只能在该方法中使用。您应该从新实例传递 id 并使用该 id 来检索对象。

redirect action: "index", id: childInstance.id

和索引可能是

def index(Long id){
    childInstance = Child.get(id)

然后可以断定不需要callChildProfile方法

或者你可以使用参数

def index(){
    childInstance = Child.get(params.id)
    if(childInstance){
        doSomething()
    }
    else{
        createOrGetOrDoSomethingElse()
    }
}
于 2012-08-29T18:40:33.310 回答