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

我的未来我决定 提交于 2020-01-11 08:46:47

问题


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?


回答1:


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




回答2:


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());



回答3:


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>



回答4:


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



来源:https://stackoverflow.com/questions/6499078/how-to-put-play-controllers-in-an-arbitrary-sub-package

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