Less Verbose way of generating Play 2's javascript router

前端 未结 5 873
北海茫月
北海茫月 2021-02-06 00:54

Currently I define my app\'s javascript router in a fairly verbose way

def javascriptRoutes = Action { implicit request =>
  import routes.javascript._
  Ok(R         


        
5条回答
  •  温柔的废话
    2021-02-06 01:18

    Expanding @rochb's answer for Play 2.4 Java, where the package names are slightly different, with support for multiple controller packages.

    public Result javascriptRoutes() throws IllegalAccessException, IllegalArgumentException,
            InvocationTargetException {
    
        // use reflection to get the fields of controllers.routes.javascript and other controller packages
        Set reverseRoutes = new HashSet();
        Class[] routeClasses = {controllers.routes.javascript.class, com.example.package1.routes.javascript.class, com.example.package2.routes.javascript.class};
        for (int i = 0; i < routeClasses.length; i++) {
            for (Field f : routeClasses[i].getFields()) {
                // get its methods
                for (Method m : getAllMethods(f.getType(), withReturnType(play.api.routing.JavaScriptReverseRoute.class))) {
                    // for each method, add its result to the reverseRoutes
                    reverseRoutes.add(m.invoke(f.get(null)));
                }
            }
        }
        // return the reverse routes
        response().setContentType("text/javascript");
        return ok(Routes.javascriptRouter("jsRoutes",
                reverseRoutes.toArray(new play.api.routing.JavaScriptReverseRoute[reverseRoutes.size()])));
    }
    
        

    提交回复
    热议问题