当我使用Play 1.2时,我能够使用@Before或@After(和其他...)在任何控制器内部注释一些方法,以便在此控制器内的每个请求之前或之后执行一个方法。
如何在Play 2.0中执行此操作?
我读了一下关于Global对象的内容,但它似乎并不是我想要的。此外,动作构图似乎对我想做的事情太复杂了。我希望看到一些更简单的东西。
有什么想法吗?
答案 0 :(得分:8)
不幸的是,您必须使用@Before
@After
,而@After
没有等价物。
对于after
,我会在结束操作结束时编写自己的public static Result index() {
....
Result result = ...;
return after(result);
}
protected static Result after(Result result) {
...
Result afterResult = ...,
return afterResult
}
方法;像这样的东西:
{{1}}
答案 1 :(得分:4)
public class Logging {
@With(LogAction.class)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Logs {
}
public static class LogAction extends Action<Logs> {
private void before(Context ctx) {
System.out.println("Before action invoked");
}
private void after(Context ctx) {
System.out.println("After action invoked");
}
public F.Promise<Result> call(Http.Context context) throws Throwable {
before(context);
Promise<Result> result = delegate.call(context);
after(context);
return result;
}
}
}
在控制器中使用@Logs进行注释。