servlet+Properties+资源文件的加载

读取资源文件

  • 文件资源读取有很多方法,但是在服务器中想得到资源的绝对路径有点困难,一般使用相对路径即可

 public class PropertiesServlet extends HttpServlet {
     /**
      * 读取资源文件
      * @param req
      * @param resp
      * @throws ServletException
      * @throws IOException
      */
     @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         //先加载编译后的文件,使其成为一个文件流,(不管怎么样使它变为一个流,对于我们来说都是好操作的)
         InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
         //使用资源加载类去加载这个流
         Properties prop = new Properties();
         prop.load(is);
         //get出我们想要的信息
         String name = prop.getProperty("username");
         String password = prop.getProperty("password");
 
         //打印验证
         resp.getWriter().print("username = " +name);
         resp.getWriter().print("password = "+password);
    }
 
     @Override
     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         super.doPost(req, resp);
    }
 }
 

 

posted @ 2020-08-02 22:40  泰坦巨猿  阅读(245)  评论(0)    收藏  举报