Sunday, July 28, 2013

How do I call/use Grails service from a gsp

We can use 'grailsApplication.classLoader.loadClass' to load service.

<%@ page import="com.myproject.MyService" %>
<%
def myService = grailsApplication.classLoader.loadClass('com.myproject.MyService').newInstance()
%>
<span>${myService.methodName()}</span>


We can use another approach

In Grails we can use the set tag to define a variable with a value on a GSP. But we can also use the same tag to access a Grails service on a GSP. We must use the bean attribute with the name of the Grails service. We can even pass the name of any Spring managed bean in the application context of our application.
In the following sample GSP we access a Grails service with the name BlogService. We invoke the method allTitles() and use the result.

<html>
<head>
<meta content="main" name="layout"/>
</head>
<body>
    %{--Use BlogService--}%
    <g:set var="blog" bean="blogService"/>
    <ul>
    <g:each in="${blog.allTitles()}" var="title">
        <li>${title}</li>
    </g:each>
    </ul>
</body>
</html>

No comments:

Post a Comment