eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

The purpose of this intro tutorial is to explore the Play Framework and figure out how we can create a web application with it.

Play is a high-productivity web application framework for programming languages whose code is compiled and run on the JVM, mainly Java and Scala. It integrates the components and APIs we need for modern web application development.

2. Play Framework Setup

Let’s head over to the Play framework’s official page and download the latest version of the distribution. At the time of this tutorial, the latest is version 2.7.

We’ll download the Play Java Hello World tutorial zip folder and unzip the file into a convenient location. At the root of this folder, we’ll find an sbt executable that we can use to run the application. Alternatively, we can install sbt from their official page.

To use sbt from the downloaded folder, let’s do the following:

cd /path/to/folder/
./sbt run

Note that we are running a script in the current directory, hence the use of the ./ syntax.

If we install sbt, then we can use it instead:

cd /path/to/folder/
sbt run

After running this command, we’ll see a statement that says “(Server started, use Enter to stop and go back to the console…)”. This means that our application is ready, therefore we can now head over to http://localhost:9000 where we’ll be presented with a Play Welcome page:

play1

3. Anatomy of Play Applications

In this section, we’ll get a better understanding of how a Play application is structured and what each file and directory in that structure is used for.

If you would like to challenge yourself to a simple example right away, then skip to the next section.

These are the files and folders we find in a typical Play Framework application:

├── app                      → Application sources
│   ├── assets               → Compiled Asset sources
│   │   ├── javascripts      → Typically Coffee Script sources
│   │   └── stylesheets      → Typically LESS CSS sources
│   ├── controllers          → Application controllers
│   ├── models               → Application business layer
│   └── views                → Templates
├── build.sbt                → Application build script
├── conf                     → Configurations files and other non-compiled resources (on classpath)
│   ├── application.conf     → Main configuration file
│   └── routes               → Routes definition
├── dist                     → Arbitrary files to be included in your projects distribution
├── lib                      → Unmanaged libraries dependencies
├── logs                     → Logs folder
│   └── application.log      → Default log file
├── project                  → sbt configuration files
│   ├── build.properties     → Marker for sbt project
│   └── plugins.sbt          → sbt plugins including the declaration for Play itself
├── public                   → Public assets
│   ├── images               → Image files
│   ├── javascripts          → Javascript files
│   └── stylesheets          → CSS files
├── target                   → Generated files
│   ├── resolution-cache     → Information about dependencies
│   ├── scala-2.11            
│   │   ├── api              → Generated API docs
│   │   ├── classes          → Compiled class files
│   │   ├── routes           → Sources generated from routes
│   │   └── twirl            → Sources generated from templates
│   ├── universal            → Application packaging
│   └── web                  → Compiled web assets
└── test                     → source folder for unit or functional tests

3.1. The app Directory

This directory contains Java source code, web templates, and compiled assets’ sources — basically, all sources and all executable resources.

The app directory contains some important subdirectories, each of which packages one part of the MVC architectural pattern:

  • models – this is the application business layer, the files in this package will probably model our database tables and enable us to access the persistence layer
  • views – all HTML templates that can be rendered to the browser are contained this folder
  • controllers – a subdirectory in which we have our controllers. Controllers are Java source files that contain actions to be executed for each API call. Actions are public methods that process HTTP requests and return results of the same as HTTP responses
  • assets– a subdirectory that contains compiled assets such as CSS and javascript. The above naming conventions are flexible, we can create our packages e.g. an app/utils package. We can also customize the package naming app/com/baeldung/controllers

It also contains optional files and directories as needed by the particular application.

3.2. The public Directory

Resources stored in the public directory are static assets that are served directly by the Web server.

This directory usually has three subdirectories for images, CSS, and JavaScript files. It’s recommended that we organize the asset files like this for consistency in all Play applications.

3.3. The conf Directory

The conf directory contains application configuration files. The application.conf is where we’ll put most of the configuration properties for the Play application. We’ll define endpoints for the app in routes.

If the application needs any extra configuration files, they should be put in this directory.

3.4. The lib Directory

The lib directory is optional and contains unmanaged library dependencies. If we have any jars that are not specified in the build system, we put them in this directory. They’ll be added automatically to the application classpath.

3.5. The build.sbt File

The build.sbt file is the application build script. This is where we list dependencies necessary to run the application, such as test and persistence libraries.

3.6. The project Directory

All the files that configure the build process based on SBT are found in the project directory.

3.7. The target Directory

This directory contains all files generated by the build system — for example, all .class files.

Having seen and explored the directory structure for the Play Framework Hello World example we just downloaded, we can now go through the fundamentals of the framework using an example.

4. Simple Example

In this section, we’ll create a very basic example of a web application. We’ll use this application familiarize ourselves with the fundamentals of the Play framework.

Instead of downloading an example project and building up from it, let’s see another way we can create a Play Framework application, using the sbt new command.

Let’s open a command prompt, navigate to our location of choice, and execute the following command:

sbt new playframework/play-java-seed.g8

For this one, we’ll need to have installed sbt already as explained in Section 2.

The above command will prompt us for a name for the project first. Next, it will ask for the domain (in reverse, as is the package naming convention in Java) that will be used for the packages. We press Enter without typing a name if we want to keep the defaults which are given in square brackets.

The application generated with this command has the same structure as the one generated earlier. We can, therefore, proceed to run the application as we did previously:

cd /path/to/folder/ 
sbt run

The above command, after completion of execution, will spawn a server on port number 9000 to expose our API, which we can access through http://localhost:9000. We should see the message “Welcome to Play” in the browser.

Our new API has two endpoints that we can now try out in turn from the browser. The first one – which we have just loaded – is the root endpoint, which loads an index page with the “Welcome to Play!” message.

The second one, at http://localhost:9000/assets, is meant for downloading files from the server by adding a file name to the path. We can test this endpoint by getting the favicon.png file, which was downloaded with the application, at http://localhost:9000/assets/images/favicon.png.

5. Actions and Controllers

A Java method inside a controller class that processes request parameters and produces a result to be sent to the client is called an action.

A controller is a Java class that extends play.mvc.Controller that logically groups together actions that may be related to results they produce for the client.

Let’s now head over to app-parent-dir/app/controllers and pay attention to HomeController.java.

The HomeController‘s index action returns a web page with a simple welcome message:

public Result index() {
    return ok(views.html.index.render());
}

This web page is the default index template in the views package:

@main("Welcome to Play") {
  <h1>Welcome to Play!</h1>
}

As shown above, the index page calls the main template. The main template then handles the rendering of the page header and body tags. It takes two arguments: a String for the title of the page and an Html object to insert into the body of the page.

@(title: String)(content: Html)

<!DOCTYPE html>
<html lang="en">
    <head>
        @* Here's where we render the page title `String`. *@
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/main.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon.png")">
    </head>
    <body>
        @* And here's where we render the `Html` object containing
         * the page content. *@
        @content

        <script src="@routes.Assets.versioned("javascripts/main.js")" type="text/javascript"></script>
    </body>
</html>

Let’s change the text in the index file a little:

@main("Welcome to Baeldung") {
  <h1>Welcome to Play Framework Tutorial on Baeldung!</h1>
}

Reloading the browser will give us a bold heading:

Welcome to Play Framework Tutorial on Baeldung!

We can do away with the template completely by removing the render directive in the index() method of the HomeController so that we can return plain text or HTML text directly:

public Result index() {
    return ok("REST API with Play by Baeldung");
}

After editing the code, as shown above, we’ll have only the text in the browser. This will just be plain text without any HTML or styling:

REST API with Play by Baeldung

We could just as well output HTML by wrapping the text in the header <h1></h1> tags and then passing the HTML text to the Html.apply method. Feel free to play around with it.

Let’s add a /baeldung/html endpoint in routes:

GET    /baeldung/html    controllers.HomeController.applyHtml

Now let’s create the controller that handles requests on this endpoint:

public Result applyHtml() {
    return ok(Html.apply("<h1>This text will appear as a heading 1</h1>"));
}

When we visit http://localhost:9000/baeldung/html we’ll see the above text formatted in HTML.

We’ve manipulated our response by customizing the response type. We’ll look into this feature in more detail in a later section.

We have also seen two other important features of the Play Framework.

First, reloading the browser reflects the most recent version of our code; that’s because our code changes are compiled on the fly.

Secondly, Play provides us with helper methods for standard HTTP responses in the play.mvc.Results class. An example is the ok() method, which returns an OK HTTP 200 response alongside the response body we pass to it as a parameter. We’ve already used the method displaying text in the browser.

There are more helper methods such as notFound() and badRequest() in the Results class.

6. Manipulating Results

We have been benefiting from Play’s content negotiation feature without even realizing it. Play automatically infers response content type from the response body. This is why we have been able to return the text in the ok method:

return ok("text to display");

And then Play would automatically set the Content-Type header to text/plain. Although this works in most cases, we can take over control and customize the content type header.

Let’s customize the response for HomeController.customContentType action to text/html:

public Result customContentType() {
    return ok("This is some text content").as("text/html");
}

This pattern cuts across all kinds of content types. Depending on the format of the data we pass to the ok helper method, we can replace text/html by text/plain or application/json.

We can do something similar to set headers:

public Result setHeaders() {
    return ok("This is some text content")
            .as("text/html")
            .withHeader("Header-Key", "Some value");
}

7. Conclusion

In this article, we have explored the basics of the Play Framework. We’ve also been able to create a basic Java web application using Play.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)