从context.xml文件获取数据库凭据

问题描述 投票:0回答:2

我有一个在Eclipse中实现一些API的java项目。

我有db.java文件,可以与MySQL数据库进行通信。

我想在/META-INF/context.xml文件中使用它们,而不是在java文件中使用MySQL凭据。

你知道怎么做吗?

这是我目前的代码:

public class db {

    private String userName = null;
    private String password = null;
    private String dbName = null;
    private String db_connect_string = null;

    public db() {
        this.db_connect_string = "jdbc:mysql://localhost/mydb";
        this.dbName = "name";
        this.userName = "uname";
        this.password = "pass";
    }

protected Connection getDBMySQLCon() {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        return DriverManager.getConnection(this.db_connect_string+"?useSSL=false",  this.userName, this.password);
    } catch (ClassNotFoundException | SQLException | InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}
java mysql eclipse
2个回答
1
投票

您可以拥有一个包含所需信息的属性文件,而不是XML文件。 XML文件的问题在于您必须选择XML解析器并使用它。

如果要继续使用属性文件,可以考虑以下代码段。

public void setProp() throws Exception{  
    FileReader reader=new FileReader("db.properties");  
    Properties p=new Properties();  
    p.load(reader);  
    // you can get values you want as properties using
    this.db_connect_string = p.getProperty("db_connect_string");  
    this.dbName = p.getProperty("dbName");  
}  

你的文件结构应该是这样的

db_connect_string=connection.string  
dbName=name
userName=uname
password=pass

1
投票

这是容器环境的一部分。

/meta-inf/context.XML

context.xml会覆盖tomcat上下文条目。

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <!-- Specify a JDBC datasource -->
    <Resource name="jdbc/mydatabase" 
              auth="Container"
              type="javax.sql.DataSource" 
              username="YOUR_USERNAME" 
              password="YOUR_PASSWORD"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://mysql.metawerx.net:3306/YOUR_DATABASE_NAME?
              autoReconnect=true"
              validationQuery="select 1"
              maxActive="10" 
              maxIdle="4"/>

</Context>

// Get DataSource
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mydatabase");
// Get Connection and Statement
Connection c = ds.getConnection();
Statement s = c.createStatement();
© www.soinside.com 2019 - 2024. All rights reserved.