Is there a way to attach to events like asp.net's "Application_Start" and "Begin_Request" in Java/Tomcat/JSP web projects? I would really rather not use JSF or an extra framework(Spring, Struts). I do not want to do it on a per-page basis with anything like 'jspInit', a global event handler is the goal.
In the event that I am stuck in the .net way of doing things, the point is to have a central place to initialize IoC containers (Application_Start), and implement a 'One database transaction per request' workflow (Begin_Request).
Thanks.
In the Java EE (Servlets+JSPs) world, the equivalent functionality can be obtained by implementing the relevant interfaces standardized by the Java EE specification.
The equivalent of the Application concept is the Web Context or the Servlet context. Sessions and Requests are the same concept in Java EE as .Net. There are relevant listener classes that need to be implemented in order to hook onto the relevant events in
More information on this can be found in the Java EE 5 tutorial on the Servlet lifecycle. The interfaces continue to hold good for Java EE 6 as well.
If you've read the comments, you would have noticed that it is possible to do preprocessing and postprocessing of requests by implementing a ServletRequestListener
or a Filter
.
I would suggest that you utilize Filter
s (as did BalusC). This is because the Filter
will be invoked everytime a request is sent to a particular URL, and is often the most effective way of ensuring that all requests to a URL receive the same 'treatment'.
The reasons for this are found in the Java EE API documentation on the ServletRequestListener
:
Interface for receiving notification events about requests coming into and going out of scope of a web application.
A ServletRequest is defined as coming into scope of a web application when it is about to enter the first servlet or filter of the web application, and as going out of scope as it exits the last servlet or the first filter in the chain.
When you use a ServletRequestListener
, you must note that the requestInitialized and requestDestroyed events are fired only once per request (unlike the Filter
where the doFilter method is invoked everytime the Filter
is invoked in a processing pipeline). Since Filters are the usual way of performing actions before and after requests (I haven't seen a lot of people use ServletRequestListeners), I would suggest that you utlize filters in such a context.
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