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.
Filters vs ServletRequestListener
If you’ve read the comments, you would have noticed that it is possible to do preprocessing and postprocessing of requests by implementing a
ServletRequestListeneror aFilter.I would suggest that you utilize
Filters (as did BalusC). This is because theFilterwill 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:When you use a
ServletRequestListener, you must note that the requestInitialized and requestDestroyed events are fired only once per request (unlike theFilterwhere the doFilter method is invoked everytime theFilteris 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.