# Play Framework ###### source: [Play Framework 2.5 Documentation](https://www.playframework.com/documentation/2.5.x/JavaHome) ## Actions, Controllers, Results Requests received by a Play application is handled by an **action** (Java method), and it returns a **Result**. A **controller** class groups several action methods. ## Routing Play recommends dependency-injection routers (and controllers), as opposed to static routers. Routes are defined in `conf/routes/` ### Dynamic route path ``` GET /client/:id controllers.Clients.show(id: Long) ``` ### Dynamic route path with regex ``` GET /items/$id<[0-9]+> controllers.Items.show(id: Long) ``` ### Reversing URL ```java= public class Application extends Controller{ public Result hello(String name){ return ok("Hello "+name); } //Redirects to /hello/Bob public Result index(){ return redirect(controllers.routes.Application.hello("Bob")); } } ``` ## Request ### Body Parser Default body parser parses `application/json` body as a `JsonNode`, and an `application/x-www-form-urlencoded` as a `Map<String, String[]>`. Accessing the request body is as follows: ```java= public Result index(){ JsonNode json = request().body().asJson(); return ok("Name is: "+json.get("name").asText()); } ``` ## Response ### Setting HTTP Response Headers ```java= public Result index(){ response().setHeader(CACHE_CONTROL, "max_age=3600"); response().setHeader(ETAG,"xxx"); return ok("<h1>Hello world!</h1>").as("text/html"); } ``` ### Setting Cookies ```java= response().setCookie("cookie1_value","cookie2_value"); ``` ## Asynchronous HTTP Handling Asynchronous requests are handled using a promise API, `CompletionStage<Result>`, which, when redeemed, returns the `Result` object. Actions are asynchronous by default (`Result`s are internally enclosed in a promise). ### Sending Async Results ```java= public CompletionStage<Result> index(){ return CompletableFuture .supplyAsync(()-> intensiveComputation()) .thenApply(i-> ok("result: "+i)); } ```