Servlet读取properties文件信息

1.新建properties文件,例如写数据库的账号密码

username=root
password=root

2.把资源对象读取进来并变成流

InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/prop.properties");//把资源变成流

/WEB-INF/classes/prop.properties 是查看maven加载后路径获得
Servlet读取properties文件信息_第1张图片

3.生成properties对象,加载流,并获取数据

 		Properties prop = new Properties();
        prop.load(is);
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        resp.getWriter().print(username+":"+password);

完整代码如下

public class demo3 extends HttpServlet {
     
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/prop.properties");//把资源变成流
        Properties prop = new Properties();
        prop.load(is);
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        resp.getWriter().print(username+":"+password);


    }

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

输出结果
Servlet读取properties文件信息_第2张图片

你可能感兴趣的:(javaweb)