`
FireFlyWithCat
  • 浏览: 87363 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

在grails框架中导入groovy脚本方法(三)

阅读更多
在grails框架中导入groovy脚本方法(三)
在PluginService中定义一个方法
def getScript(scriptName, params){ 
//定义一个方法getScript(),scriptName是脚本文件名,params是这个脚本用到的参数
String scriptPath = "../yourPath/script/" //存放文件的路径
GroovyScriptEngine gse = new GroovyScriptEngine(scriptPath)
def ss = gse.loadScriptByName(scriptName) //通过文件名得到这个script
Binding binding = new Binding(); 
binding.setVariable("service2", new PluginService()) 
binding.setVariable("params", params); //上文说过这个是绑定上下文环境
def controllerScript = gse.createScript(scriptName, binding)
controllers.put(scriptName, controllerScript)  //这是定义缓存
return gse.run("${scriptName}", binding)  //运行脚本
}

这个例子是我用到的,在这个例子中gse得到的是整个controller中的目录,也就是script文件中所有的script都在这个里面。你也可以取得一个script,这样子
Gse.loadScriptByName(String name)
这就取到了一个script,后面的两个binding都是给这个script添加变量和上下文环境,也可以理解是初始化,
在下面两句就是添加缓存
最后一句是,运行这个script,后面的binding就是这个环境和变量
例如:我有一个脚本test.groovy
如:从上文中传过来的params是:params.a="world"
//test.groovy
String b="Hello"
String c=params.a+b
println params.a
println b
println c

输出:
world
Hello
Hello world!
这个就是我刚开始用的方法,但是,我勒个去啊!领导又说:在script中能够写闭包、方法、还要能够import 我们现在工程中的domain、controller、service,我去啊!这就是实现所有跟domain、controller、service相同一个数据层啊!唉!这个方法也不行啊!不过,下一个章就会有新方法!
高手不要喷啊!我是新手!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics