Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use play! framework to develop webservice? [closed]

How do I use play to develop webservice?

I cannot find any documents in the official site.

like image 772
LionPlayer Avatar asked Dec 22 '10 19:12

LionPlayer


People also ask

Why play framework is used?

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.

Is Play Framework MVC?

Play Framework is an open-source web application framework which follows the model–view–controller (MVC) architectural pattern.

Is play a Java framework?

Play is a high-productivity web application framework for programming languages whose code is compiled and run on the JVM, mainly Java and Scala.


1 Answers

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/

like image 200
Codemwnci Avatar answered Sep 18 '22 16:09

Codemwnci