How do I use play to develop webservice?
I cannot find any documents in the official site.
Play Framework makes it easy to build web applications with Java & Scala. Play is based on a lightweight, stateless, web-friendly architecture. Built on Akka, Play provides predictable and minimal resource consumption (CPU, memory, threads) for highly-scalable applications.
Play Framework is an open-source web application framework which follows the model–view–controller (MVC) architectural pattern.
Play is a high-productivity web application framework for programming languages whose code is compiled and run on the JVM, mainly Java and Scala.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With