在servlet中读取配置文件的方法有三种
1.直接用IO流读取配置文件
设置路径时比较麻烦(不推荐使用)
2.使用ServletContext类中的getRealPath()方法获取完全路径(配置文件)
然后用IO流读取配置文件(推荐使用)
package cn.liangfeng.properties;import java.io.FileInputStream;import java.io.IOException;import java.io.PrintWriter;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 GetRealPath_properties extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取properties对象 Properties p = new Properties(); //获取servlet对象 ServletContext sc = getServletContext(); //getRealPath获取指定文件的完全路径(带盘符的路径),该文件要在webroot下 String path = sc.getRealPath("/db.properties"); //获取要操作文件的输入流 FileInputStream fis = new FileInputStream(path); //将输入流加载到properties对象中 p.load(fis); // // 根据键获取文件中的值 String url = p.getProperty("url"); String username = p.getProperty("username"); String password = p.getProperty("password"); // 打印获取的值 System.out.println("url---" + url); System.out.println("username---" + username); System.out.println("password---" + password); // 在网页上打印提示语 response.getWriter().write("GetRealPath_properties"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}
3.使用ServletContext类中的getResourceAsStream()方法
设置路径时有些麻烦(不推荐使用)
我们在开发中使用第二种方法即可,方便快捷.另外两种方法的代码我就不贴了.