如何创建可重用的Grails控制器助手方法,可以在许多控制器中使用?
是的,不,我在一个控制器里有很少的私人方法。我想和其他控制人员分享。
我希望能接触到对讲机,重定向等。
发布于 2014-05-19 12:35:16
控制器之间共享代码的正确方法是将逻辑抽象为服务。看见
http://grails.org/doc/latest/guide/services.html
注意,如果服务不需要是事务性的,则应该将其标记为事务性服务。
但是,如果您有与web相关的逻辑(例如将模板或标记写入输出流),那么您也可以使用标记库来共享逻辑,因为可以从控制器调用标记。请参见:
http://grails.org/doc/latest/guide/theWebLayer.html#tagsAsMethodCalls
发布于 2014-05-17 14:13:59
您可以使用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是在运行时应用的,因此有一些开销。
发布于 2014-05-17 10:40:33
最简单的答案是使用一组静态方法在src中创建一个类,并将所有内容作为参数传递,请参见:http://grails.org/doc/2.3.8/guide/single.html#conventionOverConfiguration
...or创建一个控制器基类,所有其他控制器都是从它扩展而来的?
尽管如此,我想知道你是否真的在寻找范围内的服务?见http://ldaley.com/post/436635056/scoped-services-proxies-in-grails。
https://stackoverflow.com/questions/23709590
复制相似问题