For WebApps, web.xml can be used to store application settings. How can I read this file. My servlets run in a GlassFish v2 server.
Add an init-param:
<init-param>
<param-name>InitParam</param-name>
<param-value>init param value</param-value>
</init-param>
Then read it from java code (within a servlet):
String initParam = getServletConfig().getInitParameter("InitParam");
Not sure I fully understand this question...
Assuming your Servlet extends HttpServlet
?
HttpServlet
implements ServletConfig
, so you can find out servlet specific parameters using:
In web.xml
<servlet>
<servlet-class>com.acme.Foo</servlet-class>
<init-param>
<param-name>my.init.param</param-name>
<param-value>10</param-value>
</init-param>
</servlet>
In servlet:
int x = Integer.parseInt(getInitParameter("my.init.param"));
Similarly, you can get global (context-wide) settings using:
<context-param>
<param-name>my.context.param</param-name>
<param-value>Hello World</param-value>
</context-param>
In servlet:
String s = getServletContext.getInitParameter("my.context.param");
Of course, if you're using a framework along with your servlets, such as Spring, then you can use Spring's configuration files instead to inject settings into your web-app classes.
Doekman, is it possible to explain why you want to read the web.xml file? The settings in this file are targeted to the WebContainer. If you want to pass configuration parameters to be loaded by your application, then just use Context Parameters:
If you really needs to read the file, then I'm pretty sure you can try to load the file using Java IO. The only thing you need to know is the working path used by Glassfish when your application is running. You could try something like this System.getProperty("user.dir");
From there you can load the file using a relative path. Examples on www.exampledepot.com.
The choice of container shouldn't be relevant to this question, as each container should implement the servlet container specification, be it Tomcat, Glassfish or one of the many others.