简单问题: 我有一个服务类(比如说 helpersService )和一个方法 def constructURI(params)。 如何从模板视图中调用此方法。

我尝试了以下代码但没有成功

<% def helpersService  = new HelpersService() // or def helpersService
%>
<img src="${helpersService. constructURI(params)}"/>

但我得到以下结果:

No signature of method: com.HelpersService. constructURI() is applicable for argument types...

或(如果我使用 def helpersService

Cannot invoke method constructURI() on null object 

有什么想法吗?

有帮助吗?

解决方案

服务不适合在视图中使用。您可以创建一个TagLib,您可以通过依赖注入获取对服务的引用。

其他提示

假设您的视图由Controller呈现,一种更简单的方法是将操作的引用从操作传递到模型中的视图,即:

class someController {
  def someService
  def someAction = {
    render(view: 'someView', model: ['someService': someService])
  }
}

然后可以在视图中使用它。对于由视图呈现的模板,显然您还需要将引用传递给模板。但是要清楚,S。Puchbauer是对的;服务实际上不应该在视图中使用,并且您可能会遇到难以诊断的问题,尤其是与事务和Hibernate会话相关的问题。

我发现,这个常规的内联代码可以工作:

<% def xxxService = application.getAttribute("org.codehaus.groovy.grails.APPLICATION_CONTEXT").getBean("xxxService") %>

您可以像这样调用服务的功能:

<g:select optionKey="key" from="${xxxService.getWhateverList()}" name="tarif" value="${accountInstance?.tarif}" ></g:select>

我找到了一个使用以下代码的解决方法:

def helpersService = grailsApplication.classLoader.loadClass('HelpersService').newInstance()

然而,最好通过依赖注入使用Service,所以我将尝试Siegfried的建议。

您可以使用set tag:

轻松完成此操作,而无需创建标记库
<g:set var="versionService" bean="versionService"/>
...
<p>version ${versionService.clientVersion}</p>

我在这里找到了这个解决方案: http: //mrhaki.blogspot.com/2013/08/grails-goodness-use-services-in-gsp.html

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top