如何在非servlet java文件中读取上下文参数/ web.xml值?
我有一个常规的java文件,我用它来更新和查询mysql数据库但是我需要在该文件中使用可配置选项(如主机名,密码等)并将其放在web.xml文件中(或者可能是另一个文件,如果这是一个选项,但理想情况下在web.xml中)。
但我不知道如何从常规的非servlet java文件中访问web.xml值。
或者我是否需要读取xml(与任何其他xml文件一样……或者是否有快捷路径…)
您需要将所需参数放在web.xml文件的env-entry条目中:
dbhost java.lang.String localhost
然后通过jndi上下文访问它们
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");
您可以在web.xml和javax.servlet.ServletContextListener中使用context-parameters来填充一些静态字段。
在普通的java类中,你会读到这个静态字段。
... Prameter myParam 123456790 ...
您可以使用ServletContext.getInitParameter
访问此上下文参数
一种方法是读取xml文件并解析它。
在ServletContextListener
中解析之后,您可以将它放在一些静态映射中
实现ServletContextListener
:
package util; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class MyConfigListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext ctx = sce.getServletContext(); String hostname = ctx.getInitParameter("my.config.hostname"); // now go and do something with that } @Override public void contextDestroyed(ServletContextEvent sce) {} }
不要忘记在web.xml
注册它:
somewhere.example.org my.config.hostname util.MyConfigListener
创建一个静态类,该类将从其中一个servlet init初始化 。