2011-11-09 67 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