在动态Web项目中处理配置(数据库登录和密码等)的正确方法是什么?

Ken*_*Ken 6 passwords configuration jsp servlets

我刚刚开始使用JSP进行动态Web编程.处理配置的正确方法是什么?

例如,数据库名称,主机,登录名和密码,以及服务器中的索引目录等.我最关心的是密码的安全性.目前我将数据硬编码到.java文件中,我不认为这是正确的方法,我想从你的经验中学习.

Bal*_*usC 9

配置通常存储在属性或XML文件中,该文件放在应用程序的运行时类路径中或指定为VM参数的固定位置.可以使用java.util.PropertiesAPI 访问属性文件.可以使用JAXP或JAXB解析XML文件.

以下是此类属性文件的示例:

jdbc.url = jdbc:mysql://localhost:3306/javabase
jdbc.driver = com.mysql.jdbc.Driver
jdbc.username = java
jdbc.password = d$7hF_r!9Y

假设它被命名config.properties并且它被放置在类路径的根目录中(或者它的根路径被添加到类路径中),这里是你可以从类路径加载它的方法:

Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
String url = properties.getProperty("jdbc.url");
String driver = properties.getProperty("jdbc.driver");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
// ...
Run Code Online (Sandbox Code Playgroud)

这是一个XML文件的示例:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <jdbc>
        <url>jdbc:mysql://localhost:3306/javabase</url>
        <driver>com.mysql.jdbc.Driver</driver>
        <username>java</username>
        <password>d$7hF_r!9Y</password>
    </jdbc>
</config>
Run Code Online (Sandbox Code Playgroud)

假设它被调用config.xml并且它被放置在类路径的根目录中,这里是一个如何通过JAXP加载它的示例:

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.xml");
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(input));
XPath xpath = XPathFactory.newInstance().newXPath();
String url = (String) xpath.compile("//config//jdbc//url").evaluate(document, XPathConstants.STRING);
String driver = (String) xpath.compile("//config//jdbc//driver").evaluate(document, XPathConstants.STRING);
String username = (String) xpath.compile("//config//jdbc//username").evaluate(document, XPathConstants.STRING);
String password = (String) xpath.compile("//config//jdbc//password").evaluate(document, XPathConstants.STRING);
// ...
Run Code Online (Sandbox Code Playgroud)

它只是更冗长,尽管如果它是一个相当复杂的文件,JAXB可以让生活更轻松.

依次保护对属性或XML文件的访问权限的控制在更高(OS /平台)级别.

也可以看看: