【问题标题】:Grails Rest XML RenderingGrails Rest XML 渲染
【发布时间】:2011-11-09 22:20:27
【问题描述】:

想象一下我的控制器中有这样的场景:

def nr_1 = params.first_nr
def nr_2 = params.second_nr
def result
def erro = 'no'

if(nr_1.isInteger() && nr_2.isInteger())
    result = nr_1.toInteger() * nr_2.toInteger()
else
    erro = 'yes'

if(erro.equals('yes'))
    [sms : 'Please introduce only 2 numbers!']
else
    [sms: 'The result of the multiplication of ' + nr_1 + ' with ' + nr_2 + ' is ' + result]

这将返回到我的 gsp 视图并成功完成。现在我想将其转换为 REST 访问 Web 服务。我看到这个的方式,我将不得不手动创建这样的标签:

<firstNumber>nr_1</firstNumber>
<secondNumber>nr_1</secondNumber>   
<result>result</result>  

然后返回休息请求。我怎样才能做到这一点(通过提供 HTML 和 XML 响应,对于 XML,只解析最后的 XML 标记)。

【问题讨论】:

    标签: xml parsing rest grails groovy


    【解决方案1】:

    您可以创建一个代表您的请求的对象并将您的请求内容放入其中。

    class Multiplication
    {
      String nr_1
      String nr_2
      String result
    }
    

    它将使您能够通过render as XML 在您的操作中生成您的 XML:

    def multiplication = new Multiplication(nr_1: params.first_nr,
                                            nr_2: params.second_nr)
    def error = 'no'
      if (multiplication.nr_1.isInteger() && multiplication.nr_2.isInteger())
        multiplication['result'] = multiplication.nr_1.toInteger() * multiplication.nr_2.toInteger()
      else
        error = 'yes'
    
    if (error == 'yes')
    {
      [sms: 'Please introduce only 2 numbers!']
    }
    withFormat {
      html sms: "The result of the multiplication of $multiplication.nr_1 with $multiplication.nr_2 is $multiplication.result"
      xml { render multiplication as XML }
    }
    

    别忘了在控制器的开头import grails.converters.*

    【讨论】:

      【解决方案2】:

      控制器中的 withFormat 可能对您有用吗? giude

      【讨论】:

        猜你喜欢
        • 2010-11-30
        • 2017-06-05
        • 1970-01-01
        • 2017-09-17
        • 2011-05-17
        • 2017-01-15
        • 1970-01-01
        • 2012-03-27
        • 1970-01-01
        相关资源
        最近更新 更多