您的位置:首页 > 编程语言 > Java开发

JavaWeb学习记录(八)——servlet获取配置信息

2015-06-30 16:25 363 查看
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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: