Programmatically add a route to Play2.0

In game 1.2.X we could do

Router.addRoute("GET", "/somePath", "controller.methodName"); 

I am writing a module that adds a “route” that will be handled by the controller in the module. This is an OAuth handler and wants it easy for users not to deal with OAuth handshakes, etc.

How to do it in Play 2.0?

+6
source share
4 answers

You cannot programmatically add Routes to the object, but you can intercept web requests and process them yourself by overriding GlobalSettings.onRouteRequest . For instance:

 override def onRouteRequest(request: RequestHeader): Option[Handler] = { //do our own path matching first - otherwise pass it onto play. request.path match { case "/injectedRoute" => Some(controllers.Application.customRoute) case _ => Play.maybeApplication.flatMap(_.routes.flatMap { router => router.handlerFor(request) }) } } 

I don't know if this is recommended, but it works for me. Here's a sample on github: https://github.com/edeustace/play-injected-routes-example

+8
source

I'm not sure you can.

The concept behind Play 2.0 was to focus on type safety, including file routes. The routes file is now compiled, not interpreted at run time. If you look at the code for the routes file, it generates the scala class from the routes file itself. Therefore, runtime manipulations are simply ignored.

Unfortunately, it seems that your routes should be defined in the routes file if you do not want to intercept HTTP requests to check for specific routes yourself, which apparently means that the documentation links are / @ in the ApplicationProvider scala class.

Also see error message https://play.lighthouseapp.com/projects/82401/tickets/12-support-multiple-routes-file-and-inclusion

+3
source

You can add a shared route to the routes file (at the end of the file, because its priority will be estimated based on its location of the ad)

 GET /:page controllers.Application.showPage(page) 

Put your logic that you want to execute at runtime in the controller class

 public static Result showPage(String page){ if(page.contains("abc"){ ..... } else { //return 404 } } 

I'm not sure if this will meet your requirements, but in most scenarios this will be enough.

+3
source

* play2.0 * * Add this line to your routes file * GET / somePath controller.methodName ()

-9
source

Source: https://habr.com/ru/post/912989/


All Articles