2011-11-09 41 views
0

想象一下我这种情况在我的控制器:Grails的休息XML渲染

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标记)。

回答

0

您可以创建代表您的请求的对象,并把它你的要求的内容。

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.*

0

可能在withFormat在控制器会为你有用吗? giude

+0

是一部分,我知道。但我该如何做xml部分? – recoInrelax