如何创建可在许多控制器中使用的可重用Grails控制器帮助器方法?
正确,我在一个控制器中有几个私有方法。我想与其他控制器共享。
我想访问参数, 重定向等
在控制器之间共享代码的正确方法是将逻辑抽象到一个服务中。看到
http://grails.org/doc/latest/guide/services.html请注意,如果不要求服务是事务性的,则应将其标记为事务性的。
如果你有web相关的逻辑(如编写模板或标记到输出流),那么你也可以使用标签库来共享逻辑,因为标签可以从控制器中调用。看到:
http://grails.org/doc/latest/guide/theWebLayer.html tagsAsMethodCalls
你可以使用Mixins来放置你所有的常用代码:
// File: src/groovy/com/example/MyMixin.groovy
class MyMixin {
private render401Error() {
response.status = 401
def map = [:]
map.message = "Authentication failed"
render map as JSON
}
}
现在在控制器中你可以这样做:
// File: grails-app/controller/com/example/OneController.groovy
@Mixin(MyMixin)
class OneController {
public someAction() {
if (!user.isAuthenticated) {
// Here we're using the method from the mixin
return render401Error()
}
}
}
最后一个建议:Mixins是在运行时应用的,所以有一点开销。
最简单的答案是在src中创建一个带有一堆静态方法的类,并将所有内容作为参数传递,参见:http://grails.org/doc/2.3.8/guide/single.html#conventionOverConfiguration
…或者创建一个控制器基类,所有其他控制器扩展?
也就是说,我想知道您是否真的在寻找有作用域的服务?参见http://ldaley.com/post/436635056/scoped-services-proxies-in-grails。