Documentation

You are viewing the documentation for the 2.6.x development release. The latest stable release series is 2.4.x.

§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 forRouter method:

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 httpPort method:

F.Promise<WSResponse> response = ws.url(
    "http://localhost:" + server.httpPort() + "/hello/world"
).get();

You can configure the server by passing in a port and/or mode:

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 stop method:

server.stop();

Note: Play requires an application secret to be configured in order to start. This can be configured by providing an application.conf file in your application, or using the play.crypto.secret system property.

Next: 詳細なトピック


このドキュメントの翻訳は Play チームによってメンテナンスされているものではありません。 間違いを見つけた場合、このページのソースコードを ここ で確認することができます。 ドキュメントガイドライン を読んで、お気軽にプルリクエストを送ってください。