Web读取配置文件得到数据库连接

虽然用Java测试过,通过读取配置文件来得到数据库的连接字符串成功了,但是使用Web的时候,还是碰到了路径问题,经过调试,终于找到了规律。

database.properties

Java代码

jdbc.drivers=oracle.jdbc.driver.OracleDriver

jdbc.url=jdbc:oracle:thin:@localhost:1521:ORCL

jdbc.username=scott

jdbc.password=tiger

DatabaseUtil

Java代码

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;

}

}

路径问题已经做了注释,在这里就不多讲了。

现在写一个测试页面。

connTest.jsp

Java代码

<%@ 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" mce_href="styles.css">

-->


</head>


<body>

<%

DatabaseUtil dbUtil = DatabaseUtil.getInstance();

Connection conn = dbUtil.getConnection();

out.println(conn);

out.println("获取连接成功!");

%>

</body>

</html>


你可能感兴趣的:(Web,数据库连接,配置文件)