package day11.lwb.b_resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ResourceDemo extends HttpServlet {
/**
*读取web应用下的资源文件
*例如 properties
*路径:web项目下: /day11/WebRoot/WEB-INF/db.properties
*
*特别注意:web项目中最好不要用相对路径”.”,它表示的路径只在tomcat服务器的bin目录下
*下面演示了两种在web项目中获取读取文件的路径的方法
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
Properties prop = null;
try {
// prop = getResource1();
prop = getResource2();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String user = prop.getProperty("user");
String password = prop.getProperty("password");
System.out.println("user = "+user);
System.out.println("password = "+password);
}
**//方法1:getRealPath方法**
private Properties getResource1() throws Exception {
String path = this.getServletContext().getRealPath("/WEB-INF/db.properties");
System.out.println(path);
File file = new File(path);
FileInputStream in = new FileInputStream(file);
Properties prop = new Properties();
prop.load(in);
return prop;
}
**//方法2:getResourceAsStream方法**
private Properties getResource2() throws Exception {
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/db.properties");
Properties prop = new Properties();
prop.load(in);
return prop;
}
}

本文介绍了一种在Java Web应用中读取配置文件的方法。通过使用servlet上下文的getRealPath方法和getResourceAsStream方法,可以有效地从Web项目的WEB-INF目录中加载db.properties文件,并从中读取属性设置。

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



