Grails コントローラーで XML を解析しようとしています - GET の結果を正常に解析できますが、PUT を受信すると、要求から値を取得できません。コードは次のとおりです。
テスト: (解析と保存をテストできるように、ダミーの Person を 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 がGPathResult
...であることもわかりますが、 .text()
(and .toString()
) は常に returnnull
です。最初log.info
の出力は次のとおりです。
2013-07-09 20:04:07,862 [main] INFO client.ServiceController - Received person - 123-abcsome stuff
だから私は内容が出くわしたことを知っています。
すべての提案に感謝します。私はしばらくの間これを試してきましたが、私の知恵の終わりです。