How do I call a Grails service from a gsp?

后端 未结 4 760
一整个雨季
一整个雨季 2020-12-05 02:33

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.

And no, I

相关标签:
4条回答
  • 2020-12-05 03:06

    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.

    0 讨论(0)
  • 2020-12-05 03:09
    <%@ 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

    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)

    0 讨论(0)
  • 2020-12-05 03:11

    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" />

    In your taglib folder (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:

    package com.something
    
    class MyService {
    
    def anotherService // This will be auto-wired
    
    def method() {
        anotherService.anotherMethod()
    }
    
    }
    
    0 讨论(0)
  • 2020-12-05 03:21

    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>
    

    Refer this

    Also this is not a recommened thing, you can always use taglib

    0 讨论(0)
提交回复
热议问题