I’ve a normal Java EE Web-application which does not use any of the frameworks like Struts, JSF etc. In this web-application, I’ve a custom XML (custom-config.xml) file
which has a list of configurations specific to that application. I don’t want to mention this configuration information in web.xml file. Now when the container first
initializes any of the servlet, I need to read the configuration information mentioned in custom-config.xml file. To achieve this I have created a custom Servlet Class say CustomServlet which
extends from HttpServlet and all my Servlets will extend frm this CustomServlet. So when the Serlvet Class loads, my CustomServlet class will also be loaded.
In my CustomServlet class, I have a static method which is expected to load custom-config.xml file and understand the configurations mentioned in this.
I’ve two questions.
Is this the correct way to go about this? Or should I put this in the init() method of CustomServlet class?
How do I load the custom-config.xml file from classpath? I can’t use ServletConfig.getResourceAsStream() since I’m trying to load custom-config.xml from static method.
Doing it in a static method makes no sense. It would not be possible to get
ServletContextfrom there. You need to do it in theinit()method. You could use astatic AtomicBooleanto check if it has already been loaded in the current JVM.Alternatively, use a
ServletContextListener.You could put the parsed XML results in application scope to make it available to all servlets.
See also: