Reputation: 1948
I have a method in my controller which sends a JSON response to my GSP for jQuery to use like this:
if (someCondition) {
render(contentType: 'text/json') {
["success": false, "message": "<p>Hello user.</p>"]
}
}
In trying to follow good Grails practices, I want to move this method into a service in order to lean down controller code. My questions is, how would I get this response from the service to the controller? What kind of an object is it? I need to know this so I can preserve it and deliver it from my service to my controller which can then send it off to the GSP. Ideally, I need in my service, a variable that I can set equal to what I just put in the code box but I know its not a String type I can use to hold that JSON response. So what can I use?
Upvotes: 1
Views: 985
Reputation: 457
You could use given below code to solve your problem.
import grails.converters.JSON
if (someCondition) {
render ["success": false, "message": "<p>Hello user.</p>"] as JSON
}
And don't forgot to import
import grails.converters.JSON
Upvotes: 2
Reputation: 50275
Controller should be responsible for doing at most these tasks:
Based on that, your logic can be simplified as below:
import static org.springframework.http.HttpStatus.*
class MyController {
def myService
def myAction() {
// Validate request
// Call service class
def result = myService.serviceMethod()
//response status code
def status = result.success ? OK.value() : NOT_FOUND.value()
// render response
render(contentType: 'application/json', status: status) {
result
}
}
}
//service or any other utility class
@Transactional
class MyService {
def serviceMethod() {
if( someCondition ) {
// Return a Map if someCondition statisfies
// DO NOT put html tags other than in GSPs or message proeperties
[success: false, "message": "Hello user."]
} else {
[success: true, "message": "Hello qualified user."]
}
}
}
Also note, service class is Singleton and Transactional by default, which means, it maintains state across requests. Any property added at class level will maintain a state for more than one request which would lead to erroneous states. If there is no db writes anticipated in service class then Transactional can be turned off by removing the @Transactional
annotation.
Upvotes: 1