PlayFramework Application Global Settings
Posted By : Kiran Sharma | 31-Jan-2018
In playframework we need to create one Global class that will extend GlobalSettings class. The object of Global class in our project helps us in handling global settings for our application. Global class object must be defined in root package of the project. If you want to personalize package or class name you must modify application.global key into conf/application.conf.
GlobalSettings provides a way to intercept requests and execute business logic before a request is dispatched to an action.
=>At the time of application startup and shutdown if we want to perform some operation we can override the onStart and onStop methods and we can write our task in that.
=> To intercept requests and execute business logic before a request is dispatched to an action we can override onRequest method..
=> If at the time of an exception we want to redirect on error page , then we can override onError method.
“We can handle the life cycle of our application in play framework.”
Below is the code to tell where we can put our tasks to do at the start up and end of the application and before intercepting the request if we want to handle something that also we can perform.
Example:
import play.*;
import play.mvc.*;
@Component
public class Global extends GlobalSettings {
@Override
public void onStart(Application app) {
Logger.info("Application has started");
}
@Override
public void onStop(Application app) {
Logger.info("Application shutdown...");
}
@Override
public Result onError(RequestHeader request, Throwable t) {
return internalServerError(views.html.errorPage(t));
}
@Override
public Action onRequest(Request request, Method actionMethod) {
System.out.println("before each request..." + request.toString());
return super.onRequest(request, actionMethod);
}
@Override
public Result onHandlerNotFound(RequestHeader request) {
return Results.notFound(views.html.pageNotFound(request.uri()));
}
@Override
public Result onBadRequest(RequestHeader request, String error) {
return Results.badRequest("Don't try to hack the URI!");
}
}
Like onStart, onStop ,onError more methods are there. e.g. onHandlerNotFound,onBadRequest.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Kiran Sharma
Kiran has good knowledge of java with Servlets, JSPs, Spring, and hibernate frameworks. She is very honest towards her work. Her hobby is listening to music.