Reputation: 948
I put several .groovy scripts in the src/groovy/search/ folder and got astrayed on how to use them in my controller. My controller is grails-app/controller/EnvironmentController.groovy and I want to know how to import the classes like
import src.groovy.search.*
Also it's appreciated if anybody could point me to a complete explanation how the import works in Grails (namely how the groovy and java folders are included in the project and how to import them, including importing the java folder inside the groovy one). Thanks!
Edit: My grails is on 2.4.4
Upvotes: 1
Views: 3433
Reputation: 8587
Use and IDE: (Grails 2 or less GGTS/STS) (Grails 3 Intelij community edition)
Ctrl + shift + o all together
Ctrl + Alt + o all together
In your case, if you are using vi or some text editor then all you need is :
import search.*
i.e. remove src.groovy.
Upvotes: 0
Reputation: 2188
Imports in Grails works in same fashion as in Java. You put your groovy files under src/groovy and java files under src/java. While importing simply import with the package name and no need to include src or groovy in import.
For how to execute groovy scripts in controller or anywhere, you can't just import them. I am assuming you are talking about groovy script and not groovy class. To execute a groovy script, you have two choices.
Suppose you Sample.groovy script file contains below code
public void sayHello(String name) {
println "Say Hello to $name..."
}
public static void sayStaticHello(String name) {
println "Say Static Hello to $name..."
}
So in order to execute it in your controller you can do either:
def script = new GroovyShell().parse(new File('<Path to SampleScript.groovy>'))
script.sayHello("Sandeep Poonia")
script.sayStaticHello("Sandeep Poonia")
or
//for non-static methods
this.class.classLoader.loadClass("SampleScript").newInstance().invokeMethod("sayHello", "Sandeep Poonia")
//for static method
this.class.classLoader.loadClass("SampleScript").invokeMethod("sayStaticHello", "Sandeep Poonia")
Upvotes: 1