java获取Weblogic JNDI数据源

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shangshaohui2009/article/details/51967523
public class ReadDataSourceJNDI {

private final static Map<String, String> dbconfig = new HashMap<String, String>();
static {
Properties p = new Properties();
//采用类加载器加载配置文件(内容:jndiName=localTest)
InputStream is = ReadDataSourceJNDI.class.getResourceAsStream("/dbconfig.properties");
try {
p.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(p.getProperty("jndiName"));
//将读取到内容放置到map中
dbconfig.put("dataSource", p.getProperty("jndiName"));
}

public static Connection getConnection() {
Context ctx = null;
DataSource dsa = null;
Connection conn= null;
if (dbconfig.get("dataSource") != null) {
String DSname = dbconfig.get("dataSource");
System.out.println("数据源---》"+DSname);
try {
ctx = new InitialContext();
dsa = (DataSource) ctx.lookup(DSname);
conn = dsa.getConnection();
} catch (SQLException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
}
} else {
throw new RuntimeException("数据源名称");
}
//返回连接
return conn;

}

}


------------测试,采用servlet-------

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {

String sql = "select t.t_id, t.t_name from t_frient t";
Connection connection = null;
PreparedStatement pStatement = null;
ResultSet rs = null;
List<Friend> friends = new ArrayList<Friend>();

try {
//获取连接
connection = ReadDataSourceJNDI.getConnection();
pStatement = connection.prepareStatement(sql);
rs = pStatement.executeQuery();

while (rs.next()) {
friends.add(new Friend(rs.getInt("t_id"), rs.getString("t_name")));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ReadDataSourceJNDI.release(rs, pStatement, connection);
} catch (SQLException e) {
e.printStackTrace();
}
}

for (Friend f : friends) {
System.out.println(f);
}

// friends.add(new Friend(100, "张三"));
// friends.add(new Friend(100, "张三"));
// friends.add(new Friend(100, "张三"));

request.setAttribute("friends", friends);

request.getRequestDispatcher("/friendsList.jsp").forward(request, response);

}

猜你喜欢

转载自blog.csdn.net/shangshaohui2009/article/details/51967523