package donghongyujava.test_jdbc;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test_jdbc extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取ServletContest对象
ServletContext sct = this.getServletConfig().getServletContext();
// 获取需要解析的文件所在服务器的绝对路径
String realPath = sct.getRealPath("/WEB-INF/classes/jdbc.properties");
System.out.println(realPath);
// 根据绝对路径创建File的对象那个
File jdbc = new File(realPath);
// 打印流对象
displayProps(new FileInputStream(jdbc));
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
public void displayProps(InputStream inStream) throws IOException {
// 创建properties操作对象
Properties prop = new Properties();
// 把流对象载入
prop.load(inStream);
// 获取所有的键名称
Enumeration<?> enums = prop.propertyNames();
// 遍历结果集
while (enums.hasMoreElements()) {
//获取集合的每个元素,即获取键名称
String key = (String) enums.nextElement();
//根据键获取所对应的值
String value = prop.getProperty(key);
//输出
System.out.println(key + "==" + value);
}
}
}
jdbc.properties文件内容
url=jdbc\:mysql\://localhost\:3306/java_web
user=admin
pass=root
效果图