How to use play! framework to develop webservice?

2019-01-22 22:13发布

问题:

How do I use play to develop webservice?

I cannot find any documents in the official site.

回答1:

Quite simple really.

Play comes with a number of methods that you can use to expose your actions as web services.

For example

render()
renderJSON()
renderXML()

These can all be used to render data in a particular way.

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);
    }
}

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

To setup the route to format correctly, then add the following line to your route file

GET /webservices/sum                 Application.sum(format:'xml')

The sum.xml would then look something like

<response>
  <sum>${result}</sum>
</response>

The same concept works for 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.

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/