How to store string values in tomcat context.xml

資料庫用來連線的帳密, 不想寫死在 source code 裡, 就需要寫在外部檔案中, 寫在實體檔案又怕被 tomcat web server 存取到, 網路上還滿多解法, 也有人是放到 bean 裡.

What is the best practice to deploy database config (username/password) with Java web-app (web.xml)?
https://stackoverflow.com/questions/3762108/what-is-the-best-practice-to-deploy-database-config-username-password-with-jav

比較簡單的作法是, 直接放字串在 tomcat 的 context.xml 中.

You can use an Environmenttag:
https://stackoverflow.com/questions/18404219/how-to-store-string-values-in-context-xml

<Context>
    <Environment name="myConnectionURL" value="amqp:5272//blah.example.com&amp;param1=4" type="java.lang.String"/>
</Context>

And you can read it almost as you specified in the question:

InitialContext initialContext = new InitialContext();
Context environmentContext = (Context) initialContext.lookup("java:/comp/env");
String connectionURL = (String) environmentContext.lookup("myConnectionURL");

或是範例 2:
https://stackoverflow.com/questions/47888047/get-database-credentials-from-context-xml-file

This is part of the environment of the container.

/META-INF/context.xml

The context.xml overides the tomcate context entry.

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

source code:

// 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();

實際取用 context.xml 裡的設定值,程式碼如下:

InitialContext initContext = null;
try {
    initContext = new InitialContext();
    dataSource = (DataSource)initContext.lookup("java:comp/env/jdbc/mydatabase");
} catch (NamingException e) {
    e.printStackTrace();
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *