简体   繁体   中英

Pass value from grails controller to a class inside src/groovy

I have a Grails application. I want to use a value from Grails controller class (say MyController) inside a class in src/groovy/MyClass.groovy

How can I pass the value from Grails controller class to this class? I couldn't find anything relevant.

I tried this:

class MyController {
def name = "myapp"
}

Class MyClass{
def username = MyController.name
}

Please correct me . Thanks

It is hard to say for sure without knowing what you are doing but your probably want to pass the value as an argument to a method in MyClass and you probably don't want the value to be a field in the controller class.

class MyController {
    def someControllerAction() {
        def name = // I don't know where you are
                   // getting this value, but you got it from somewhere

        def mc = new MyClass()
        mc.someMethod(name)
        // ...
    }
}

class MyClass {
    def someMethod(String name) {
        // do whatever you want to do with the name
    }
}

Or you could pass the value as a constructor argument:

class MyController {
    def someControllerAction() {
        def name = // I don't know where you are
                   // getting this value, but you got it from somewhere

        def mc = new MyClass(name: name)
        // ...
    }
}

class MyClass {
    def name
}

I hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM