我正在尝试在 Grails 控制器中解析 XML - 我可以成功解析 GET 的结果,但是在接收 PUT 时,我无法从请求中获取值。代码如下。
测试:(放置一个假人,以便我可以测试解析和保存)
import grails.test.mixin.*
import grails.test.mixin.domain.DomainClassUnitTestMixin
import org.junit.*
import com.mycompany.stuff.Person
@TestFor(ServiceController)
@TestMixin(DomainClassUnitTestMixin)
class ServiceControllerTests {
void testCreateWithXML() {
mockDomain(Person)
request.method = "PUT"
def controller = new ServiceController()
controller.request.contentType = 'text/xml'
controller.request.content = '''
<person>
<refId>123-abc</refId>
<otherThing>some stuff</otherThing>
</person>
'''.stripIndent().getBytes() // note we need the bytes (copied from docs)
def response = controller.create()
assert Person.count() == 1
assertEquals "123-abc", Person.get("123-abc").id
}
}
控制器:在映射到 create 方法后(正确地)接收 put。
class ServiceController {
...
def create() {
if (request.format != "xml") {
render 406 // Only XML expected
return
}
def requestBody = request.XML
def objectType = requestBody.name() as String
log.info "Received ${objectType} - ${requestBody}"
if (!(objectType.toLowerCase() in ['person','personsubtype']))
{
render (status: 400, text: 'Unknown object type received in PUT')
return
}
def person = new Person(id: requestBody.person.refId.text())
person.save()
log.info "Saved ${person}"
render 200
}
使用调试器,我可以看到当接收到请求时,变量requestBody作为NodeChild接收,并且name()
是正确的。我还可以看到requestBody.person.refId
变量的 metaClass 是 of GPathResult
... 但是.text()
(and .toString()
) 总是 return null
。第一个log.info
打印输出:
2013-07-09 20:04:07,862 [main] INFO client.ServiceController - Received person - 123-abcsome stuff
所以我知道内容是偶然的。
任何和所有建议表示赞赏。我已经尝试了一段时间,但我束手无策。