When I was using Play 1.2, I was able to annotate some methods inside any controller with @Before or @After (and others...) in order to execute a method before or after each request inside this controller.
How can I do this in Play 2.0?
I read a little bit about the Global object, but it doesn't seem to be what I am looking for. Also, action composition seems way too complex for what I want to do. I hope to see something simpler.
Any ideas?
Play is rock-solid and used by hundreds of thousands of Java and Scala developers every month. Play is still extremely relevant to today's application and web development and has a passionate and very capable community around it ensuring that it has many good years left.
Play uses the Akka HTTP server backend to implement HTTP requests and responses using Akka Streams over the network. Akka HTTP implements a full server stack for HTTP, including full HTTPS support, and has support for HTTP/2. The Akka HTTP server backend is the default in Play.
Play web applications can be written in Scala or Java, in an environment that may be less Java Enterprise Edition-centric.
Unfortunately, you'll have to use action composition for the @Before
, and there is no equivalent for the @After
.
For the @After
, I'd write my own after
method at the end of end action; something like this:
public static Result index() {
....
Result result = ...;
return after(result);
}
protected static Result after(Result result) {
...
Result afterResult = ...,
return afterResult
}
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;
}
}
}
Annotate with @Logs in your controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With