Warm tip: This article is reproduced from stackoverflow.com, please click
playframework scala

How to get list of all Route URL strings in play framework?

发布于 2020-03-27 10:30:16

I have many controllers in my play 2.4.x application.

I want to get a list of all route URLs pointing their respective controllers. I know how to get the URL from the current request. But I need a list of all the URLs available inside a play application.I want to generate this list dynamically because URLs can be changed/added/deleted in future.

So,is there some way I can generate this URL list dynamically ? Or do I have the obligation to store all the URLs statically somewhere in cache or dictionary ?

oblivion 2017-06-21 15:04

I obtained the desired list by using the documentation method provided by Router trait. The documentation method returns Seq[(String, String, String)] .Here each tuple has the format:

( {http-method} , {url} , {controller method} )

The Router trait is extended by all the autogenerated Routes.scala classes. Scala-compiler generated a separate Routes.scala for each routes file in the application. These auto-generated Routes.scala files implement all the methods of Router trait including the documentation method that we discussed above.

So,to get list of all URLs, I simply had to inject the Router trait and then access the documentation method:

import play.api.routing.Router

class MyClass @Inject()(router: Router) {
 def getAllURLs:Seq[String] = router.documentation.map(k => k._2)