我有一个常规的java文件,用于更新和查询mysql数据库,但我需要在该文件中使用可配置选项(如主机名,密码等)并将其放在web.xml文件中(或者可能是另一个文件,如果这是一个选项,但理想情况下在web.xml中。)
但我不知道如何从常规的非servlet java文件中访问web.xml值。
或者我是否需要读取xml(与任何其他xml文件一样......或者是否有快捷路径...)
答案 0 :(得分:30)
您需要将所需参数放在web.xml文件的env-entry条目中:
<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>
然后通过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");
答案 1 :(得分:10)
您可以在web.xml中使用context-parameters,并使用javax.servlet.ServletContextListener填充一些静态字段。
在普通的java类中,你会读到这个静态字段。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
...
<context-param>
<description>Prameter</description>
<param-name>myParam</param-name>
<param-value>123456790</param-value>
</context-param>
...
</web-app>
您可以使用ServletContext.getInitParameter
答案 2 :(得分:3)
一种方法是读取xml文件并解析它。
在ServletContextListener
答案 3 :(得分:1)
实施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
注册:
<context-param>
<param-value>somewhere.example.org</param-value>
<param-name>my.config.hostname</param-name>
</context-param>
<listener>
<listener-class>util.MyConfigListener</listener-class>
</listener>
答案 4 :(得分:0)
创建一个静态类,该类将从servlets init之一初始化。