使用ServletContext读取配置文件信息
第一步:新建配置文件


新建一个servlet


我们知道要读取properties文件 但是不知道他的路径如何写
我们可以先运行
查看发送到服务器后的路径

doGet方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/info.properties");
Properties prop = new Properties();
prop.load(is);
String username =prop.getProperty(“username”);
String sex = prop.getProperty(“sex”);
resp.getWriter().print(username+" : "+sex);
}
web.xml中注册servlet

运行程序

本文介绍了如何在Servlet中通过ServletContext读取`/WEB-INF/classes/info.properties`配置文件。首先,利用`getResourceAsStream()`方法获取输入流,然后加载Properties对象,读取username和sex等属性。在web.xml中注册Servlet后运行程序,即可成功读取并打印配置信息。
776

被折叠的 条评论
为什么被折叠?



