1、在resource资源下创建以下目录:
并添加信息。
注意db.properties如何在其他路径下创建可能会存在导出失败,具体参考maven的导出规范。
2、实现类:
public class ServletDemo5 extends HelloServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取target下的相对路径
InputStream is=this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop=new Properties();
prop.load(is);
String user=prop.getProperty("username");
String pwd=prop.getProperty("password");
resp.getWriter().print(user+":"+pwd);
}
}
3、注册web.xml
4、访问页面
数据已读取到并渲染。