怎么玩玩!开发Web服务的框架? [英] How to use play! framework to develop webservice?
问题描述
我如何使用play来开发Web服务?
How do I use play to develop webservice?
我在官方网站上找不到任何文件.
I cannot find any documents in the official site.
推荐答案
真的很简单.
播放带有许多方法,可用于将操作公开为Web服务.
Play comes with a number of methods that you can use to expose your actions as web services.
例如
render()
renderJSON()
renderXML()
这些都可以用于以特定方式呈现数据.
These can all be used to render data in a particular way.
如果您有一个Web服务,让我们假设一个RESTful Web服务,您想返回两个数字的和,则可以通过以下方式进行操作
If you had a web service, let's assume a RESTful webservice, that you wanted to return the sum of two numbers, you could do so in the following way
public class Application extends Controller {
public static void sum(Float num1, Float num2) {
Float result = num1 * num2;
render(result);
}
}
如果将路由设置为使用XML作为格式,或者在请求标头中正确设置了格式,则可以使用称为app/views/Application/sum.xml
if your route is set up to use XML as the format, or the format is set correctly in the request header, you then return the result using a normal groovy template called app/views/Application/sum.xml
要设置路由以正确设置格式,然后将以下行添加到您的route
文件
To setup the route to format correctly, then add the following line to your route
file
GET /webservices/sum Application.sum(format:'xml')
然后sum.xml看起来像
The sum.xml would then look something like
<response>
<sum>${result}</sum>
</response>
相同的概念适用于JSON.
The same concept works for JSON.
但是,如果您不想使用常规模板,则可以简单地使用renderJSON
/renderXML
方法创建XML或JSON,但这确实意味着您正在控制器中构建表示逻辑.练习.
If however you don't want to use groovy templates, you could simply create the XML or JSON using the renderJSON
/ renderXML
methods, but this does mean you are building presentation logic into your controller, which is bad practice.
作为子注释,如果您想使用Web服务,请使用play.libs.WS类.我写了一篇关于如何做到这一点的博客
As a subnote, if you want to consume webservices, then you use the play.libs.WS class. I have written a blog on how to do that
http://playframework.wordpress.com/2010/08/15/web-services-using-play/
这篇关于怎么玩玩!开发Web服务的框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!