How to put Play! controllers in an arbitrary sub-p

2019-02-22 18:35发布

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
      |- index.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?

4条回答
萌系小妹纸
2楼-- · 2019-02-22 18:51

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...

查看更多
老娘就宠你
3楼-- · 2019-02-22 18:52

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>
查看更多
Fickle 薄情
4楼-- · 2019-02-22 19:00

You need to define the route on conf/routes. Something like: * /account/${action} account.Account.${action}

查看更多
smile是对你的礼貌
5楼-- · 2019-02-22 19:10

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());
查看更多
登录 后发表回答