How can I call a method in one of my controller classes without grails trying to generate a view?
The key to implementing REST actions is the respond method introduced in Grails 2.3. The respond method tries to produce the most appropriate response for the requested content type (JSON, XML, HTML etc.) For example, to implement the index action, simply call the respond method passing the list of objects to respond with:
The render controller method writes directly to the response, which is the most common behaviour. To instead obtain the result of template as a String you can use the render tag: Notice the usage of the g namespace which tells Grails we want to use the tag as method call instead of the render method.
Grails also has the concept of templates. These are useful for partitioning your views into maintainable chunks, and combined with Layouts provide a highly re-usable mechanism for structured views. Grails uses the convention of placing an underscore before the name of a view to identify it as a template.
A common requirement with a REST API is to expose different versions at the same time. There are a few ways this can be achieved in Grails. A common approach is to use the URI to version APIs (although this approach is discouraged in favour of Hypermedia). For example, you can define the following URL mappings:
You can redirect to another controller action.
class PuppyController {
def woof() {
redirect(action:'bark')
}
def bark(){
response.write "Moo"
}
}
At some point you should either write to the response or redirect to a method/closure that corresponds to a view so the user can receive the output.
If the method you're trying to call is on another controller, chances are YOAR DOING IT WRONG.
If, for example, I have a controller method that uploads a file, and another method that creates the filename for that file as a combination of some convention I make up (say timestamp + "pretty file for" + username) on another controller, you should promote that controller method to a Service and inject it into both controllers.
class FooController {
def fooAction() {
render("Successful call to fooAction")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With