怎么用玩!开发webservice的框架? [英] How to use play! framework to develop webservice?

查看:26
本文介绍了怎么用玩!开发webservice的框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 play 开发 webservice?

How do I use play to develop webservice?

我在官方网站上找不到任何文件.

I cannot find any documents in the official site.

推荐答案

其实很简单.

Play 附带了许多方法,您可以使用这些方法将您的操作公开为网络服务.

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.

如果你有一个网络服务,让我们假设一个 RESTful 网络服务,你想返回两个数字的总和,你可以通过以下方式来做

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 的普通 groovy 模板返回结果

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.

但是,如果您不想使用 groovy 模板,您可以简单地使用 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.

作为子注,如果您想使用网络服务,那么您可以使用 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/网络服务使用播放/

这篇关于怎么用玩!开发webservice的框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆