§Embedding a Play server in your application
While Play apps are most commonly used as their own container, you can also embed a Play server into your own existing application. This can be used in conjunction with the Twirl template compiler and Play routes compiler, but these are of course not necessary, a common use case for embedding a Play application will be because you only have a few very simple routes.
The simplest way to start an embedded Play server is to use the
Server factory methods. If all you need to do is provide some straightforward routes, you may decide to use the Routing DSL, so you will need the following imports:
import play.Mode; import play.routing.RoutingDsl; import play.server.Server; import static play.mvc.Controller.*;
Then you can create a server using the
Server server = Server.forRouter(new RoutingDsl() .GET("/hello/:to").routeTo(to -> ok("Hello " + to) ) .build() );
By default, this will start a server on a random port in test mode. You can check the port using the
F.Promise<WSResponse> response = ws.url( "http://localhost:" + server.httpPort() + "/hello/world" ).get();
You can configure the server by passing in a
Server server = Server.forRouter(new RoutingDsl() .GET("/hello/:to").routeTo(to -> ok("Hello " + to) ) .build(), Mode.TEST, 19000 );
To stop the server once you’ve started it, simply call the
Note: Play requires an application secret to be configured in order to start. This can be configured by providing an
application.conffile in your application, or using the
Next: Detailed topics
Found an error in this documentation? The source code for this page can be found here. After reading the documentation guidelines, please feel free to contribute a pull request.