jdbc.properties内容如下:
jdbcUrl=jdbc:mysql://localhost:3306/animal
user=root
pass=root
servlet获取资源信息代码如下
public class ResourceServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
test1();
test2();
}
//方法一
private void test1() throws IOException, FileNotFoundException {
System.out.println("--------------test1--------------");
ServletContext application=getServletContext();
String path=application.getRealPath("/WEB-INF/classes/jdbc.properties");
File file=new File(path);
Properties pro=new Properties();
pro.load(new FileReader(file));
System.out.println(pro.getProperty("jdbcUrl"));
System.out.println(pro.getProperty("user"));
System.out.println(pro.getProperty("pass"));
}
//方法二
private void test2() throws IOException, FileNotFoundException {
System.out.println("--------------test2--------------");
ServletContext application=getServletContext();
URL url=application.getResource("/WEB-INF/classes/jdbc.properties");
Properties pro=new Properties();
pro.load(url.openStream());
System.out.println(pro.getProperty("jdbcUrl"));
System.out.println(pro.getProperty("user"));
System.out.println(pro.getProperty("pass"));
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}