2017-12-19 3 views
0

EclipseにいくつかのAPIを実装したJavaプロジェクトがあります。context.xmlファイルからデータベースの資格情報を取得

私はdb.javaファイルを持っており、MySQLデータベースとの通信が可能です。

javaの資格情報をJavaファイルに入れる代わりに、/META-INF/context.xmlファイルに入れたいと思います。

あなたはこれを行う方法を知っていますか?

これは私の現在のコードです:代わりにXMLファイルの

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; 
} 
+0

「web.xml」のコンテキストパラメータを設定してください – Satya

+0

@Satya私に例を挙げてください。 – zinon

+0

あなたが使用しているテクノロジー – Satya

答えて

1

、必要な情報を持っているプロパティファイルを、持つことができます。 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はtomcateコンテキストエントリをoverides。

<?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(); 
関連する問題