读取资源文件

Propertise

  • 在java目录下新建propertise
  • 在resource下新建propertise

发现:都被打包到了同一个路径下:Classes,我们俗称这个路径为classpath;

1.需要一个文件流

username=root
password=123456

2.需要一个Servlet

package com.xf2021.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Get extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/aa.properties");
        Properties prop = new Properties();
        prop.load(is);
        String user=prop.getProperty("username");
        String pwd=prop.getProperty("password");
        resp.getWriter().println(user+":"+pwd);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
}

注:获取资源的方式可以理解为,先用 this.getServletContext().getResourceAsStream 创建一个新的对象,将Properties的数据保存在“is”中,然后创建一个 Properties 对象来对is中的数据用 prop.getProperty 进行读取,最后进行赋值打印

3.需要将Servlet写入web.xml

  <servlet>
    <servlet-name>get</servlet-name>
    <servlet-class>com.xf2021.servlet.Get</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>get</servlet-name>
    <url-pattern>/getdata</url-pattern>
  </servlet-mapping>

4.测试成功


You got to put the past behind you before you can move on.