很抱歉这么久才回复。我在让一切正常工作时遇到了一些麻烦。非常感谢@Dónal 的所有帮助。结束使用以下类来解决问题:
import org.codehaus.groovy.grails.web.servlet.HttpHeaders;
import org.springframework.http.HttpStatus;
import grails.artefact.Artefact;
import grails.rest.RestfulController;
import grails.transaction.Transactional;
@Artefact("Controller")
@Transactional(readOnly = true)
class MyRestfulController<T> extends RestfulController<T> {
public MyRestfulController(Class<T> resource, boolean readOnly = false) {
super(resource, readOnly);
}
@Override
@Transactional
def save() {
if(handleReadOnly()) {
return
}
T instance = createResource(getParametersToBind())
instance.validate()
if (instance.hasErrors()) {
respond instance.errors, view:'create' // STATUS CODE 422
return
}
instance.save flush:true
def formatHolder = params.format ? this : request
formatHolder.withFormat {
form multipartForm {
flash.message = message(code: 'default.created.message', args: [message(code: "${resourceName}.label".toString(), default: resourceClassName), instance.id])
redirect instance
}
'*' {
response.addHeader(HttpHeaders.LOCATION,
g.createLink(
resource: this.controllerName, action: 'show',id: instance.id, absolute: true,
namespace: hasProperty('namespace') ? this.namespace : null ))
respond instance, [status: HttpStatus.CREATED]
}
}
}
@Override
@Transactional
def update() {
if(handleReadOnly()) {
return
}
T instance = queryForResource(params.id)
if (instance == null) {
notFound()
return
}
instance.properties = getParametersToBind()
if (instance.hasErrors()) {
respond instance.errors, view:'edit' // STATUS CODE 422
return
}
instance.save flush:true
def formatHolder = params.format ? this : request
formatHolder.withFormat {
form multipartForm {
flash.message = message(code: 'default.updated.message', args: [message(code: "${resourceClassName}.label".toString(), default: resourceClassName), instance.id])
redirect instance
}
'*'{
response.addHeader(HttpHeaders.LOCATION,
g.createLink(
resource: this.controllerName, action: 'show',id: instance.id, absolute: true,
namespace: hasProperty('namespace') ? this.namespace : null ))
respond instance, [status: HttpStatus.OK]
}
}
}
}
通过使用def formatHolder = params.format ? this : request
然后调用formatHolder.withFormat
,我现在能够独立于请求格式覆盖响应格式。
它还不适用于 Accept Header,但至少它有效。