JNDI配置数据源

一、WebRoot/META-INF/context.xml



       
二、web.xml

   
      JNDI DataSource
      jdbc/scsis
      javax.sql.DataSource
      Container
   
三、Constants.java

package com.x.util;

import java.util.ResourceBundle;

public final class Constants {
	/** Oracle数据源URL. */
	public static final String JDBC_DATASOURCE_URL;
	static {
		ResourceBundle bundle = ResourceBundle.getBundle("config");
		JDBC_DATASOURCE_URL = bundle.getString("jndi.jdbc.connector");
	}
}
四、config.properties

jndi.jdbc.connector=java:/comp/env/jdbc/scsis
五、Utility.java

package com.x.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class Utility {
	private static final Logger log = Logger.getLogger(Utility.class);
	
	/**
	 * 获取数据库连接
	 */
	public static Connection getConnection() {
		try {
			InitialContext initial = new InitialContext();
			// 使连接池初始化
			DataSource dataSource = (DataSource) initial
					.lookup(Constants.JDBC_DATASOURCE_URL);
			Connection con = dataSource.getConnection();
			return con;
		} catch (SQLException exp) {
			logDBError(exp);
			return null;
		} catch (Exception ex) {
			logError(ex);
			return null;
		}
	}

	/**
	 * 记录异常
	 */
	public static synchronized void logError(Exception exp) {
		StackTraceElement ste[] = exp.getStackTrace();
		StringBuffer content = new StringBuffer();
		content.append("[" + exp.toString() + "]\n");
		for (int i = 0; i < ste.length; i++) {
			content.append("  " + ste[i].toString() + "\n");
		}
		log.error(content);
	}

	/**
	 * 记录数据库异常
	 */
	public static synchronized void logDBError(Exception exp) {
		StackTraceElement ste[] = exp.getStackTrace();
		StringBuffer content = new StringBuffer();
		content.append(exp.toString());
		for (int i = 0; i < ste.length; i++) {
			content.append("  " + ste[i].toString() + "\n");
		}
		log.error(content);
	}
	
}







你可能感兴趣的:(Jndi)