[英]How do I call a Grails service from a gsp?
How can I invoke a service directly from a view? 如何直接从视图调用服务? I'm trying with
${my.domain.service.method}
, but it complains it can't find the property. 我正在尝试使用
${my.domain.service.method}
,但它抱怨它无法找到该属性。
And no, I don't want to use a controller because the view is a template. 不,我不想使用控制器,因为视图是模板。
Best to use the tag library because creating a service instance directly in the view via the class loader WILL NOT autowire other services declared that may live in the service you are trying to use. 最好使用标记库,因为通过类加载器直接在视图中创建服务实例不会自动发送可能存在于您尝试使用的服务中的其他声明的服务。
Using the tag library you will have auto-wiring of those services. 使用标记库,您将自动连接这些服务。
In your gsp view <g:customTag param1="$modelObjec" param2="someString" />
在你的gsp视图中
<g:customTag param1="$modelObjec" param2="someString" />
In your taglib folder ( yourApp/grails-app/taglib/com/something/MyAppTagLib
): 在您的taglib文件夹中(
yourApp/grails-app/taglib/com/something/MyAppTagLib
):
package com.something
class MyAppTagLib {
def myService // This will be auto-wired
def customTag = { attribs ->
def modelObj = attribs['param1']
def someString = attribs['param2']
// Do something with the params
myService.method()
out << "I just used method of MyService class"
}
}
Your MyService: 你的MyService:
package com.something
class MyService {
def anotherService // This will be auto-wired
def method() {
anotherService.anotherMethod()
}
}
Try this - much helpful 试试这个 - 非常有帮助
%{--Use BlogService--}%
<g:set var="blog" bean="blogService"/>
<ul>
<g:each in="${blog.allTitles()}" var="title">
<li>${title}</li>
</g:each>
</ul>
Also this is not a recommened thing, you can always use taglib 这也不是一个推荐的东西,你总是可以使用taglib
I think the best way of doing it is: 我认为最好的方法是:
<%
def myService = grailsApplication.mainContext.getBean("myService");
%>
This way, you get the service instance without losing the autowired services. 这样,您可以获得服务实例而不会丢失自动服务的服务。
<%@ page import="com.myproject.MyService" %>
<%
def myService = grailsApplication.classLoader.loadClass('com.myproject.MyService').newInstance()
%>
And then you can call ${myService.method()}
in your gsp view 然后你可以在你的gsp视图中调用
${myService.method()}
Be aware that calling transactional service methods from views hurts performance. 请注意,从视图调用事务服务方法会损害性能。 Better to move all your transactional service method calls to the controller (if you can)
最好将所有事务性服务方法调用移动到控制器(如果可以)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.