package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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;
/**
* servlet中庸servletContext读取资源文件
*/
public class ServletDemo11 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
// 资源文件在src下,那么在web服务器中的位置是WEB-INF/classes下
// /代表web程序的根目录
InputStream in = this.getServletContext().getResourceAsStream(
"/WEB-INF/classes/db.properties");
//资源在包中,那么在web服务器中的位置是WEB-INF/classes/package下
InputStream in = this.getServletContext().getResourceAsStream(
"/WEB-INF/classes/test/db.properties");
//资源在WebRoot下,那么在web服务器中的位置是web程序的根目录下
InputStream in = this.getServletContext().getResourceAsStream(
"/db.properties");
read(in);
*/
//chuanTong();
chuanTong2();
}
/**
* 传统的SE读取资源文件方式是错误的:
*/
public void chuanTong() {
//在src下
try {
//这样是读取不出来的,因为相对路径是相对于虚拟机加载的路径,也就是tomcat启动时的bin目录
//所以在web程序中读取资源时要用servletContext对象
FileInputStream fin = new FileInputStream("WEB-INF/classes/db.properties");
read(fin);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 传统的SE读取资源文件方式是错误的:
* 但是如果先用servletContext对象拿到资源的绝对路径是可以的
* 而且这种方法还有个好处就是可以得到文件的名称,getResourceAsStream是不能获取资源名称的
* 比如做下载时,就需要拿到资源名称
*/
public void chuanTong2() {
//在src下
try {
String path = this.getServletContext().getRealPath("WEB-INF/classes/db.properties");
String name = path.substring(path.lastIndexOf("\\")+1);
System.out.println("文件名称" + name);
FileInputStream fin = new FileInputStream(path);
read(fin);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param in
* @throws IOException
* 抽取出来的代码
*/
private void read(InputStream in) throws IOException {
Properties prop = new Properties();
prop.load(in);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}