Play provides a DSL for routers directly in code. This DSL has many uses, including embedding a light weight Play server, providing custom or more advanced routing capabilities to a regular Play application, and mocking REST services for testing.
The DSL uses a path pattern syntax similar to Play’s compiled routes files, extracting parameters out, and invoking actions implemented using lambdas.
The DSL is provided by
RoutingDsl. Since you will be implementing actions, you may want to import tha static methods from
Controller, which includes factory methods for creating results, accessing the request, response and session. So typically you will want at least the following imports:
import play.api.routing.Router; import play.routing.RoutingDsl; import play.libs.F; import static play.mvc.Controller.*;
A simple example of the DSL’s use is:
Router router = new RoutingDsl() .GET("/hello/:to").routeTo(to -> ok("Hello " + to) ) .build();
:to parameter is extracted out and passed as the first parameter to the router. Note that the name you give to parameters in the the path pattern is irrelevant, the important thing is that parameters in the path are in the same order as parameters in your lambda. You can have anywhere from 0 to 3 parameters in the path pattern, and other HTTP methods, such as
DELETE are supported.
Like Play’s compiled router, the DSL also supports matching multi path segment parameters, this is done by prefixing the parameter with
Router router = new RoutingDsl() .GET("/assets/*file").routeTo(file -> ok("Serving " + file) ) .build();
Regular expressions are also supported, by prefixing the parameter with a
$ and post fixing the parameter with a regular expression in angled brackets:
Router router = new RoutingDsl() .GET("/api/items/$id<[0-9]+>").routeTo(id -> ok("Getting item " + id) ) .build();
In the above examples, the type of the parameters in the lambdas is undeclared, which the Java compiler defaults to
Object. The routing DSL in this case will pass the parameters as
String, however if you define an explicit type on the parameter, the routing DSL will attempt to bind the parameter to that type:
Router router = new RoutingDsl() .GET("/api/items/:id").routeTo((Integer id) -> ok("Getting item " + id) ) .build();
Supported types include
Boolean, and any type that extends
Asynchronous actions are of course also supported, using the
Router router = new RoutingDsl() .GET("/api/items/:id").routeAsync((Integer id) -> F.Promise.pure(ok("Getting item " + id)) ) .build();
Next: Extending Play
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. Have questions or advice to share? Go to our community forums to start a conversation with the community.