标签:j2ee myeclipse tomcat servletcontext getresourceasstream
ServletContext读取资源文件内容的方式有两种:
方法1.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/data.properties");
Properties pros = new Properties();
pros.load(in);
String username = pros.getProperty("username");
String password = pros.getProperty("password");
System.out.println("username = " + username);
System.out.println("password = " + password);
}这里需要注意的是data.properties文件的位置在Myeclipse的src目录下,为啥getResourceAsStream方法传入的参数确实"/WEB-INF/classes/data.properties"
这是因为这些代码有web服务器执行,当项目发布以后,data.properties文件就会被放到tomcat安装文件所在文件夹下。
如图:
所以这里传入参数就解释清楚了。
方法2
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = this.getServletContext().getRealPath("/WEB-INF/classes/data.properties");
FileInputStream in = new FileInputStream(path);
Properties pros = new Properties();
pros.load(in);
String username = pros.getProperty("username");
String password = pros.getProperty("password");
System.out.println("username = " + username);
System.out.println("password = " + password);
}J2EE之ServletContext读取资源文件,布布扣,bubuko.com
标签:j2ee myeclipse tomcat servletcontext getresourceasstream
原文地址:http://blog.csdn.net/m631521383/article/details/32141669