Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Getting started

1. Install sbt (Scala Build Tool)

First, you need to have sbt, the interactive build tool for Scala, installed on your machine. You can download it from the official sbt website. Follow the installation instructions specific to your operating system.

2. Create a New Play Application

Open a terminal or command prompt and run the following command to create a new Play project:

sbt new playframework/play-scala-seed.g8

This command creates a new directory with a simple Play application template. Navigate into your project directory to start working on your application.

3. Explore the Project Structure

The generated project has several important directories and files:

  • app/: Contains your Scala application code, including controllers and models.
  • conf/: Contains configuration files, including routes which defines URL mappings to controllers.
  • public/: Contains static assets like images, JavaScript, and CSS files.
  • test/: Contains tests for your application.

4. Define Routes

Open the conf/routes file. This is where you define the URLs that your application responds to. Each line in this file consists of an HTTP method, a path, and an action. For example:

GET     /hello       controllers.HomeController.hello()

5. Implement Controller Actions

Controllers handle incoming requests and return responses. They are located in the app/controllers directory. To respond to our /hello route, you could create a HomeController like this:

package controllers

import play.api.mvc._

class HomeController @Inject()(val controllerComponents: ControllerComponents) extends BaseController {

  def hello() = Action { implicit request: Request[AnyContent] =>
    Ok("Hello, Play Framework!")
  }
}

6. Run Your Application

To run your Play application, open a terminal in your project directory and execute:

sbt run

Your application will start on port 9000 by default. Open a web browser and go to http://localhost:9000/hello to see your application in action.

7. Learn More

This tutorial only scratches the surface of what you can do with the Play Framework. Here are some suggestions for next steps:

  • Explore Templates: Learn how to use Twirl, Play's templating engine, to create dynamic HTML content.
  • Database Access: Look into integrating a database using Play's built-in support for Slick or other ORMs.
  • Authentication: Implement user authentication and authorization for your application.
  • Asynchronous Programming: Utilize Play's support for asynchronous programming to handle long-running operations without blocking.

The official Play documentation is an excellent resource for in-depth exploration of these and other topics. The Scala community and Stack Overflow are also great places to find help and learn from others' experiences.