This chapter introduces several ways to define generic action functionality.java
這章節介紹幾個定義通用action功能的方式。mvc
Previously, we said that an action is a Java method that returns aplay.mvc.Result
value. Actually, Play manages internally actions as functions. Because Java doesn’t support first class functions, an action provided by the Java API is an instance of play.mvc.Action
:app
前面咱們說過,一個action就是一個返回play.mvc.Result
值的java方法。實際上,Play在內部吧action看成函數。這是由於java不支持一級函數,一個java API 提供的action是一個play.mvc.Action
實例:ide
public abstract class Action { public abstract Result call(Http.Context ctx); }
Play builds a root action for you that just calls the proper action method. This allows for more complicated action composition.函數
Play會構建根action,它僅僅用來調用恰當的action方法,這容許更復雜的action組合。ui
You can compose the code provided by the action method with anotherplay.mvc.Action
, using the @With
annotation:this
你能夠使用 @With
註解組合action方法spa
@With(VerboseAction.class)
scala
public static Result index() {
code
return ok("It works!");
}
Here is the definition of the VerboseAction
:
這是 VerboseAction
的定義:
public class VerboseAction extends Action.Simple {
public Result call(Http.Context ctx) throws Throwable {
Logger.info("Calling action for " + ctx); return delegate.call(ctx);
}
}
At one point you need to delegate to the wrapped action using delegate.call(...)
.
有時你須要用 delegate.call(...)
調用被包裹的action。
You also mix with several actions:
你也能夠把幾個action混在一塊兒使用:
@With(Authenticated.class, Cached.class)
public static Result index() {
return ok("It works!");
}
Note:
play.mvc.Security.Authenticated
andplay.cache.Cached
annotations and the corresponding predefined Actions are shipped with Play. See the relevant API documentation for more information.注意:
play.mvc.Security.Authenticated
和play.cache.Cached
註解以及相應Action在Play中已經預約義了。詳情請看相關API文檔。
You can also mark action composition with your own annotation, which must itself be annotated using @With
:
你能夠用自定義的註解來標記action組合,但它必須被 @With
註釋。
@With(VerboseAction.class)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Verbose {
boolean value() default true;
}
You can then use your new annotation with an action method:
你能夠對action方法使用新的註解:
@Verbose(false)
public static Result index() {
return ok("It works!");
}
Your Action
definition retrieves the annotation as configuration:
你的 Action
定義會象configuration那樣得到註解:
}
public class VerboseAction extends Action<Verbose> { public Result call(Http.Context ctx) { if(configuration.value) { Logger.info("Calling action for " + ctx); return delegate.call(ctx); } }
You can also put any action composition annotation directly on the Controller
class. In this case it will be applied to all action methods defined by this controller.
你也能夠直接在 Controller
上使用註解,這樣會對這個控制器的全部action方法起做用。
…
@Authenticated public Admin extends Controller { }