grails - 无法在 Grails Controller 中读取 PUT XML 请求

标签 grails groovy httprequest grails-controller

我正在尝试在 Grails Controller 中解析 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
    }
}

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变量的元类是 GPathResult ...然而 .text() (和 .toString() )总是返回 null .第一个log.info打印输出:
2013-07-09 20:04:07,862 [main] INFO  client.ServiceController  - Received person - 123-abcsome stuff

所以我知道内容是偶然的。

任何和所有建议表示赞赏。我已经尝试了一段时间,但我束手无策。

最佳答案

您正在访问 refId不恰本地来自 requestBody .在你的情况下<person>本身由 requestBody 表示.
requestBody.refId.text()会给你123-abc .

Controller 实现和测试用例应该这样写:

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

关于grails - 无法在 Grails Controller 中读取 PUT XML 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17560393/

相关文章:

Android:关于通过HTTP进行安全和用户认证(注册、登录)的一些问题

grails - Grails-重定向请求

json - gzipping 来自 grails Controller 的 json 响应

linux - 试图找到一个支持 Groovy for Linux 的 IDE

java - ElasticSearch Java API : Update Existing Document

grails - 如何检查params中是否存在参数?

asp-classic - 如何访问Http请求中的响应头

python - 通过 Python 发送多个 HTTP 请求的理想方法?

xml - 根据类层次结构创建XML

grails - 在 GORM 中重命名复合外键