Last Updated: February 25, 2016
·
2.66K
· Matt Conroy

Play 2 Javascript Router Setup in 4 Steps with Java

Setting up the javascript routing portion of Play is extremely simple, yet there isn't a simple doc to go along with it.

Step 1

Create a method that will be exposed via javascript.

controllers/Application.java

package controllers;

import play.Routes;
import play.mvc.Controller;
import play.mvc.Result;

public class Application extends Controller {
    public static Result kickTheDog() {
        return Controller.ok();
    }
}

Step 2

Create a route to the method that will be exposed via javascript.

conf/routes

GET   /kickTheDog                                           @controllers.Application.kickTheDog()

Step 3

Create a javascript routes generator for the new method.

controllers/Application.java

package controllers;

import play.Routes;
import play.mvc.Controller;
import play.mvc.Result;

public class Application extends Controller {
    public static Result jsRoutes() {
        response().setContentType("text/javascript");
        return ok(Routes.javascriptRouter("jsRoutes",
            controllers.routes.javascript.Application.kickTheDog()
            )
        );
    }

    public static Result kickTheDog() {
        return Controller.ok();
    }
}

conf/routes

GET   /kickTheDog                                           @controllers.Application.kickTheDog()
GET   /jsRoutes                                                 @controllers.Application.jsRoutes()

Step 4

Use the javascript router by including the dynamic javascript generated stub file in your scala template.

<script type="text/javascript" src="@routes.Application.jsRoutes"></script>

Now the method can be accessed via javascript like:

jsRoutes.controllers.Application.kickTheDog().ajax({
    success: function() {

    },
    error: function() {

    }
});

2 Responses
Add your response

Here is another great example of using the play 2 javascript router. http://stackoverflow.com/questions/11133059/play-2-x-how-to-make-an-ajax-request-with-a-common-button

over 1 year ago ·

very nice and simple, thank you.

over 1 year ago ·