I've got a regular java file that I use to update and query a mysql database but I need to take configurable options in that file (like host name, password, etc) and put it in the web.xml file (or perhaps another file if that's an option, but ideally in web.xml).
But I don't know how to get access to web.xml values from a regular non-servlet java file.
Or would I need to read the xml (like any other xml file... or is there a shortcut route to this...)
You need to put the required parameters in env-entry entries of your web.xml file:
<env-entry>
<env-entry-name>dbhost</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>localhost</env-entry-value>
</env-entry>
and then access them via the jndi context
import javax.naming.Context;
import javax.naming.InitialContext;
...
// Get the base naming context
Context env = (Context)new InitialContext().lookup("java:comp/env");
// Get a single value
String dbhost = (String)env.lookup("dbhost");
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