How to put Play! controllers in an arbitrary sub-package
I'm using the Play Framework for a web app in Java.
I'd like to put an Account controller in an "account" subpackage, for example:
|- controllers
|- account
|- Account.java
While my views are organized like:
|- views
|- Account
|- in开发者_StackOverflow中文版dex.html
The Account.java file contains:
package controllers.account;
import play.mvc.Controller;
public class Account extends Controller {
public static void index() {
render();
}
}
I'd like to have the following behavior:
when a request is made to http://localhost/account/{action}
, it's redirected to the Account.java
controller that shows the view in the Account
folder.
Any tips?
If you do create a package structure, note that there's a few new syntaxes that are non-obvious:
Reverse lookup of controller
Put the package name between 'controllers' and 'routes':
controllers.account.routes.Account.index
E.g. in a view
<a href="@controllers.account.routes.Account.index" class="btn">Exit</a
View references in controller
Package name follows 'views.html':
return ok(views.html.account.index.render());
Have you tried putting your views in a structure that matches your controller structure?
|- views
|- account
|- Account
|- index.html
Beside that, you can always pass in the view name to the render() call:
render("Account/index.html");
I personally would always stick to the built-in structure that is supplied with play. Otherwise you could easily end up in refactoring hell, when you rearrange your controller structure somewhere down the road...
If you want to reference a controller located in a sub package from a view and use some structure like this
|- com
|- company
|- system
|- controllers
|- MyController
|- views
|- index.html
and a route configured in conf/routes as
GET /api/hello com.company.system.controllers.MyController.hello
one can use following to create a link to the method hello from the view
<a href="@com.company.system.controllers.routes.MyController.hello">Hello!</a>
You need to define the route on conf/routes. Something like: * /account/${action} account.Account.${action}
精彩评论