簡體   English   中英

如何在非servlet java文件中讀取上下文參數/ web.xml值?

[英]How can I read context parameter/web.xml values in a non-servlet java file?

我有一個常規的java文件,用於更新和查詢mysql數據庫,但我需要在該文件中采用可配置的選項(如主機名,密碼等)並將其放在web.xml文件中(或者可能是另一個文件,如果這是一個選項,但理想情況下在web.xml中)。

但我不知道如何從常規的非servlet java文件中訪問web.xml值。

或者我需要讀取xml(就像任何其他xml文件一樣......或者是否有快捷路徑...)

您需要將所需參數放在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");

您可以在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>

您可以使用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注冊它:

<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>

創建一個靜態類,該類將從其中一個servlet init初始化

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM