play framework route that matches all

泪湿孤枕 提交于 2019-12-07 04:01:08

问题


I'm working on an angular app using play framework for my rest-services. Everything in the public folder is an angular app (stylesheets, javascripts, images and html). I want every request that is not for something in the stylesheets, javascripts, templates or images folder to be routed to the index.html page. This is so that angular routing can take over from there...

As a side note i can mention that I am going to place every restservice under /services/ which links to my own java controllers.

Is it possible in play framework 2.3.4 to define a route that catches all without having to use the matching elements?

This is my route defs so far:

GET     /                       controllers.Assets.at(path="/public", file="index.html")
GET     /stylesheets/*file      controllers.Assets.at(path="/public/stylesheets", file)
GET     /javascripts/*file      controllers.Assets.at(path="/public/javascripts", file)
GET     /templates/*file        controllers.Assets.at(path="/public/templates", file)
GET     /images/*file           controllers.Assets.at(path="/public/images", file)

#this line fails
GET     /*                      controllers.Assets.at(path="/public", file="index.html")

回答1:


It's not possible to omit usage of matching elements but you can route a client via controller. The route definition looks like this:

GET         /*path               controllers.Application.matchAll(path)

And the corresponding controller can be implemented as follows:

public class Application extends Controller {

    public static Result matchAll(String path) {
        return redirect(controllers.routes.Assets.at("index.html"));
    }

}

Update

If you don't want to redirect a client you can return a static resource as a stream. In this case a response MIME type is required.

public class Application extends Controller {

    public static Result matchAll(String path) {
        return ok(Application.class.getResourceAsStream("/public/index.html")).as("text/html");
    }

}



回答2:


For this task you can use onHandlerNotFound in Global class which will render some page without redirect:

import play.*;
import play.mvc.*;
import play.mvc.Http.*;
import play.libs.F.*;

import static play.mvc.Results.*;

public class Global extends GlobalSettings {

    public Promise<Result> onHandlerNotFound(RequestHeader request) {
        return Promise.<Result>pure(notFound(
            views.html.notFoundPage.render(request.uri())
        ));
    }

}


来源:https://stackoverflow.com/questions/25686617/play-framework-route-that-matches-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!