如何在非servlet java文件中读取上下文参数/ web.xml值? [英] How can I read context parameter/web.xml values in a non-servlet java file?

查看:113
本文介绍了如何在非servlet java文件中读取上下文参数/ web.xml值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个常规的java文件,用于更新和查询mysql数据库但我需要在该文件中使用可配置的选项(如主机名,密码等)并将其放在web.xml文件中(或者可能是另一个文件,如果这是一个选项,但理想情况下是在web.xml中。)

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

但我不知道如何从常规访问web.xml值非servlet java文件。

But I don't know how to get access to web.xml values from a regular non-servlet java file.

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

Or would I need to read the xml (like any other xml file... or is there a shortcut route to this...)

推荐答案

您需要将所需参数放在web.xml文件的env-entry条目中:

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>

然后通过jndi上下文访问它们

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");

这篇关于如何在非servlet java文件中读取上下文参数/ web.xml值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆