§Routing DSL
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 the 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.routing.Router;
import play.routing.RoutingDsl;
import java.util.concurrent.CompletableFuture;
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();
The :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 POST
, PUT
and 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 Integer
, Long
, Float
, Double
, Boolean
, and any type that extends PathBindable
.
Asynchronous actions are of course also supported, using the routeAsync
method:
Router router = new RoutingDsl()
.GET("/api/items/:id").routeAsync((Integer id) ->
CompletableFuture.completedFuture(ok("Getting item " + id))
)
.build();
§Binding Routing DSL
Configuring an application to use a Routing DSL can be achieved in many ways, depending on use case:
§Embedding play
An example of embedding a play server with Routing DSL can be found in Embedding Play section.
§Providing a DI router
A router can be provided to the application similarly as detailed in Application Entry point and Providing a router, using e.g. a java builder class:
package router;
import play.routing.Router;
import play.mvc.Controller;
import play.routing.RoutingDsl;
public class RoutingDslBuilder extends Controller{
public static Router getRouter() {
return new RoutingDsl()
.GET("/hello/:to").routeTo(to -> ok("Hello " + to))
.build();
}
}
and in the application loader:
class AppLoader extends ApplicationLoader {
def load(context: Context) = {
new MyComponents(context).application
}
}
class MyComponents(context: Context) extends BuiltInComponentsFromContext(context) {
lazy val router = Router.from {
RoutingDslBuilder.getRouter.asScala.routes
}
}
§Providing a DI router with Guice
A router via Guice could be provided with the following snippet:
@Singleton
public class GuiceRouterProvider implements Provider<play.api.routing.Router> {
private final Router javaRouter;
@Inject
public GuiceRouterProvider(RoutingDslBuilder router) {
javaRouter = router.getRouter();
}
@Override
public play.api.routing.Router get() {
return javaRouter.asScala();
}
}
and in the application loader:
public class GuiceAppLoader extends GuiceApplicationLoader {
@Override
protected GuiceableModule[] overrides(ApplicationLoader.Context context) {
GuiceableModule[] modules = super.overrides(context);
GuiceableModule module = GuiceableModule$.MODULE$.fromPlayBinding(new BindingKey<>(play.api.routing.Router.class).toProvider(GuiceRouterProvider.class).eagerly());
List<GuiceableModule> copyModules = new ArrayList<>(Arrays.asList(modules));
copyModules.add(module);
return copyModules.toArray(new GuiceableModule[copyModules.size()]);
}
}
§Overriding binding
A router can also be provided using e.g. GuiceApplicationBuilder in the application loader to override with custom router binding or module as detailed in Bindings and Modules
Next: Custom Binding
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.