Skip to content
javahacks.dev
Play Framework

Play Framework Tutorial for Java Developers Step by Step

Create a Play Framework application in Java with sbt, add a route, a controller and a template, run it in dev mode and read what Play generates.

6 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the Spring and PostgreSQL logos.

Play is a web framework for Java and Scala that is stateless, built on asynchronous I/O, and has a very short edit and refresh loop. This tutorial creates a small Java application on Play 3.0 and walks through the parts you touch every day: the project layout, a route, a controller, a template and a test. You need a recent JDK and sbt installed. How the framework handles a request is covered in Play Framework architecture, and this page only needs you to follow along.

Create the project

Shell
sbt new playframework/play-java-seed.g8
cd <the-project-name>
sbt run

The template asks for a project name and creates the directory. sbt run starts the server in development mode on http://localhost:9000 and downloads dependencies on the first run, which takes a few minutes. When the default page loads, the toolchain works and everything after this is code.

The layout

DirectoryContents
app/controllersController classes
app/viewsTwirl templates, named *.scala.html
conf/routesURL to controller mapping
conf/application.confConfiguration
public/Static assets
test/JUnit tests
build.sbtBuild definition
project/plugins.sbtsbt plugins, including Play itself

Unlike a Maven project, the source directories are not under src/main. Play's layout is flatter, and your IDE picks it up from the sbt build.

Add a route

conf/routesText
GET     /                  controllers.HomeController.index(request: Request)
GET     /hello/:name       controllers.HomeController.hello(name: String)

Each line is an HTTP method, a path and the controller action that serves it. :name captures a path segment and passes it as the parameter. The file is compiled, so a typo in a method name is a build error and does not wait for the first request. A parameter that cannot be converted to the declared type, for example text where a Long is expected, gets a 400 response before your code runs.

Write the controller

app/controllers/HomeController.javajava
package controllers;

import javax.inject.Inject;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;

public class HomeController extends Controller {

    @Inject
    public HomeController() {
    }

    public Result index(Http.Request request) {
        return ok(views.html.index.render("Welcome to Play"));
    }

    public Result hello(String name) {
        return ok("Hello, " + name);
    }
}

An action is any public method that returns a Result. ok(...) builds a 200 response with the body you give it. Controllers are created by dependency injection, with Guice by default, so anything a controller needs goes in as a constructor parameter. The Http.Request argument gives access to headers, cookies, the query string and the body. A query value is read with request.queryString("q"), which returns an Optional<String>.

Return JSON

A small API action shows how little ceremony there is:

java
public Result status() {
    return ok(Json.toJson(Map.of("service", "orders", "ok", true)));
}

Json.toJson uses Jackson and sets the content type to application/json. Add the matching line GET /status controllers.HomeController.status to the routes file. For anything beyond a demonstration, build proper request and response classes; the full version is in a REST API in Play.

Add a template

app/views/index.scala.htmlText
@(message: String)

<!DOCTYPE html>
<html>
    <head><title>Home</title></head>
    <body>
        <h1>@message</h1>
    </body>
</html>

The first line declares the template's parameters, like a method signature. @message writes a value, escaped for HTML by default, which is what prevents most cross-site scripting by accident. Twirl compiles the file to a class, views.html.index, with a typed render method, so passing the wrong type is a compile error. Loops, conditions and layouts are in Twirl templates.

See it run

With sbt run active, open http://localhost:9000/hello/ana. The page shows Hello, ana. Change the greeting in the controller, save, and reload the browser. Play recompiles on that first request and serves the new code, with no restart. A compile error appears as a page in the browser with the failing line highlighted, which is the quickest place to read it. If the build fails in a way that does not match your code, the usual fix is to stop sbt and run sbt clean, and compile errors after upgrading sbt lists the others.

Write a test

test/controllers/HomeControllerTest.javajava
public class HomeControllerTest extends WithApplication {

    @Test
    public void helloGreetsByName() {
        Http.RequestBuilder request = new Http.RequestBuilder()
                .method(GET)
                .uri("/hello/ana");

        Result result = route(app, request);

        assertEquals(OK, result.status());
        assertEquals("Hello, ana", contentAsString(result));
    }
}

WithApplication starts the application for the test, and route sends the request through the real router and filters without opening a socket. Import GET, OK, route and contentAsString statically from play.test.Helpers. Run it with sbt test.

Configuration and the dev loop

Settings live in conf/application.conf, written in HOCON, a superset of JSON that allows comments, substitutions and includes. Read a value in a controller or service by injecting Config:

java
@Inject
public HomeController(Config config) {
    this.greeting = config.getString("app.greeting");
}
conf/application.confText
app.greeting = "Hello"
app.greeting = ${?APP_GREETING}

The second line overrides the first only when the environment variable exists, which is the standard way to keep one file for every environment. A missing key throws at startup in the injected constructor, so a typo is found the first time the controller is created, not in production at three in the morning.

Dev mode and production mode behave differently in ways that matter. In dev mode the code reloads, errors render as pages, and the secret key has a development default. In production none of those hold. You start the packaged application with the script that sbt stage or sbt dist creates, and Play refuses to start without a proper secret, which is deliberate. Test the production start-up on your machine at least once before the first deployment, because a configuration mistake is much cheaper to find there.

Stateless by design

Play keeps no session on the server. State travels in a cookie signed with play.http.secret.key, or it lives in a database or a cache. Horizontal scaling therefore needs no session replication. It also means you must set a real secret in production, as shown in deploying a Play application, and never reuse the development value.

Common first-day problems

Port 9000 is already in use: a previous sbt run is still alive in another terminal. Stop it with Ctrl+D in that shell, or start this one on another port with sbt "run 9001". The browser shows a blank page after you change a template: the compile failed, and the error page only shows for requests that go through Play, so check the terminal as well. The first sbt run appears to hang: it is downloading the Scala compiler and dependencies, and sbt prints progress only now and then. A route compiles but the page returns a 404: the route order matters, and an earlier, broader pattern may be catching the path before yours. Put specific routes above general ones.

What this tutorial leaves out

You have not touched a database, forms or authentication. Continue with a JSON API in a REST API in Play, and with data in Ebean or JPA. The primary sources are the Play documentation and the Java getting-started guide.

Also inSpring MVC
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.