Web读取配置文件获得数据库链接

虽然用Java测试过,经过读取配置文件来获得数据库的链接字符串成功了,可是使用Web的时候,仍是碰到了路径问题,通过调试,终于找到了规律。 database.properties [code] jdbc.drivers=oracle.jdbc.driver.OracleDriver jdbc.url=jdbc:oracle:thin:@localhost:1521:ORCL jdbc.username=scott jdbc.password=tiger [/code] DatabaseUtil [code] package com.util; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import oracle.sql.CLOB; public class DatabaseUtil { private static DatabaseUtil dbUtil; private String drivers; private String url; private String username; private String password; //加反斜线就表示在默认包目录,不加则表示在与当前类同路径去查找该属性文件 private static String FILE_PATH_NAME = "/database.properties"; private void init() { try { InputStream in = getClass().getResourceAsStream(FILE_PATH_NAME); Properties props = new Properties(); props.load(in); in.close(); drivers = props.getProperty("jdbc.drivers"); url = props.getProperty("jdbc.url"); username = props.getProperty("jdbc.username"); password = props.getProperty("jdbc.password"); } catch (IOException e) { e.printStackTrace(); } } private DatabaseUtil() { init(); } public static DatabaseUtil getInstance() { if(dbUtil == null) { dbUtil = new DatabaseUtil(); } return dbUtil; } public Connection getConnection() { Connection conn = null; try { Class.forName(drivers); conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return conn; } } [/code] 路径问题已经作了注释,在这里就很少讲了。 如今写一个测试页面。 connTest.jsp [code] <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <jsp:directive.page import="com.util.DatabaseUtil"/> <jsp:directive.page import="java.sql.Connection"/> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'connTest.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% DatabaseUtil dbUtil = DatabaseUtil.getInstance(); Connection conn = dbUtil.getConnection(); out.println(conn); out.println("获取链接成功!"); %> </body> </html> [/code]