无法在Grails控制器中读取PUT XML请求

时间:2013-07-10 00:12:06

标签: grails groovy httprequest grails-controller

我正在尝试在Grails控制器中解析XML - 我可以成功解析GET的结果但是在接收PUT时,我无法从请求中获取值。代码如下。

测试:( PUTs一个假人,以便我可以测试解析和保存)

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
    }
}

Controller:映射到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()(和.toString())始终返回null。第一个log.info打印输出:

2013-07-09 20:04:07,862 [main] INFO  client.ServiceController  - Received person - 123-abcsome stuff

所以我知道内容已经发现。

任何和所有建议表示赞赏。我已经尝试了一段时间,并且在我的智慧结束。

1 个答案:

答案 0 :(得分:1)

您从refId不恰当地访问requestBody。在您的情况下,<person>本身由requestBody表示。

requestBody.refId.text()会给你123-abc

控制器实现和测试用例应该这样写:

def create() {
        if (request.format != "xml") {
            render 406 // Only XML expected
            return
        }

        def requestBody = request.XML
        def objectType  = requestBody.name() as String

        //You can see here objectType is person which signifies
        //requestBody is represented as the parent tag <person> 
        log.info "Received ${objectType} - ${requestBody}"
        if (!(objectType.toLowerCase() in ['person','personsubtype'])) {
            render (status: 400, text: 'Unknown object type received in PUT')
            return
        }

        //Since <person> is represented by requestBody, 
        //refId can be fetched directly from requestBody
        def person = new Person(id: requestBody.refId.text())
        person.save()

        log.info "Saved ${person}"
        render 200
    }

可以优化测试类,并删除不需要的项目: -

//Test Class can be optimized
import grails.test.mixin.*
import org.junit.*
import com.mycompany.stuff.Person

@TestFor(ServiceController)
//@Mock annotation does the mocking for domain classes
@Mock(Person)
class ServiceControllerTests {
    void testCreateWithXML() {
        //mockDomain(Person) //Not required, taken care by @Mock
        request.method = "PUT"
        //No need to initialize controller 
        //as @TestFor will provide controller.
        //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)
        controller.create()

        assert controller.response.contentAsString == 200
        assert Person.count() == 1
        assertEquals "123-abc", Person.get("123-abc").id
    }
}