0

I am new to grails, hence this question. Can we get an instance of grails controller in a service. I know that it is a bad design but the problem with me right now is that grails controller has got some properties like render, redirect,flash, message that i would like to use in the service. How can i do that ?

Manas Shukla
  • 135
  • 1
  • 9

2 Answers2

3

The general advice is "don't". Services are for reusable logic and transactional database operations, and should not generally be aware of web layer things like the session/flash/redirects etc.

A better design might be to have the service method return a value which the controller then uses to issue the appropriate redirect. Or if you need access to the flash, pass a reference to it from the controller to the service method

class SomeService {
  void storeInMap(map, k, v) { map[k] = v}
}

class SomeController {
  def someService

  def act1() {
    someService.storeInMap(flash, "hello", "world")
  }
}

For rendering templates and handling i18n messages there are alternative approaches, namely the groovyPageRenderer and messageSource Spring beans respectively.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
2

Of course you could simply pass these controller properties into the service (assuming the service is called from the controller), but in general I wouldn't recommend this. Here are some alternatives

flash

You can access the flash scope from anywhere with:

def flashScope = WebUtils.retrieveGrailsWebRequest().flashScope

message

You can get i18n messages from the properties files in a service by dependency injecting the messageSource bean, e.g.

class MyService {

  MessageSource messageSource

  def getMsg() {
    messageSource.getMessage('key', ['arg1', 'arg2'].toArray(), Locale.default)
  }
}

render

Use the pageRenderer bean to render a template from a service, e.g.

class MyService {

  PageRenderer pageRenderer

  def getTemplateContent() {
    pageRenderer.render(template: '/some/template', model: [email: 'me@something.com'])

  }
}
Dónal
  • 185,044
  • 174
  • 569
  • 824