jsp - How to auto run a Class on startup -
i have webapplication relies on initialization (ie threads needs started).
something like:
public class init { private static resource .... static { // initialization } public static void init(){} }
so putted initialization stuff in init class , in every jsp page have call .init() method... init method empty, purpose starting init class initialization. thought have initialization started once.
but still have manually call .init() method in page (or servlet)... first page called (that has initialization) needed , after point every other page secured ('cause resources initialized). has week spot, if miss 1 page, , user calls page...
is there way instruct tomcat execute initialization automatically after application start-up?
you can make use of servletcontextlistener
. have init
class implement interface. may if move initialization code static block contextinitialized()
method.
import javax.servlet.servletcontextevent; import javax.servlet.servletcontextlistener; public class init implements servletcontextlistener { private static resource; public void contextinitialized(servletcontextevent sce) { // initialization } public void contextdestroyed(servletcontextevent sce) { // empty } }
please note need register listener tomcat adding following web.xml
<listener> <listener-class>package.path.to.init</listener-class> </listener>
since, have access servletcontext
(call sce.getservletcontext()) can (if choose to) register context attribute , make available servlet or jsp within application.
Comments
Post a Comment