Kir*_*irn 19 java web.xml servlets
我有一个常规的java文件,用于更新和查询mysql数据库,但我需要在该文件中采用可配置的选项(如主机名,密码等)并将其放在web.xml文件中(或者可能是另一个文件,如果这是一个选项,但理想情况下在web.xml中).
但我不知道如何从常规的非servlet java文件中访问web.xml值.
或者我需要读取xml(就像任何其他xml文件一样......或者是否有快捷路径...)
stj*_*roe 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>
Run Code Online (Sandbox Code Playgroud)
然后通过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");
Run Code Online (Sandbox Code Playgroud)
Ral*_*lph 10
您可以在web.xml和javax.servlet.ServletContextListener中使用context-parameters来填充一些静态字段.
在普通的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>
Run Code Online (Sandbox Code Playgroud)
您可以使用访问此上下文参数 ServletContext.getInitParameter