package main.com.action.servletcfandct;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import java.util.ResourceBundle;
public class ServletContextDqpzwj extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
System.out.println("通過ServletContext讀取配置檔案");
ServletContextDq();
System.out.println("通過ResourceBundle 讀取配置檔案");
resourceBundleTest();
System.out.println("通過類加載器讀取配置檔案");
ClassLoad();
System.out.println("通過Url 讀取配置檔案");
UrlTest();
} catch (Exception e) {
e.printStackTrace();
}
}
//通過ServletContext讀取配置檔案
public void ServletContextDq() throws Exception {
ServletContext context = getServletContext();
String contextPath = context.getRealPath("/WEB-INF/classes/db.properties");
InputStream is = new FileInputStream(contextPath);
Properties properties = new Properties();
properties.load(is);
System.out.println("驅動類+"+properties.getProperty("db.driver"));
}
//通過ResourceBundle 讀取配置檔案(隻能讀取類路徑下的配置檔案)
public void resourceBundleTest(){
ResourceBundle resourceBundle=ResourceBundle.getBundle("db");
System.out.println("驅動類+"+resourceBundle.getString("db.driver"));
}
//通過類加載器讀取配置檔案隻能讀取classes 和類路徑下的任意資源
public void ClassLoad() throws Exception{
//InputStream is= ServletContextDqpzwj.class.getClassLoader().getResourceAsStream("db.properties");
InputStream is= ServletContextDqpzwj.class.getClassLoader().getResourceAsStream("main/com/action/servletcfandct/db.properties");
Properties properties = new Properties();
properties.load(is);
System.out.println("驅動類+"+properties.getProperty("db.driver"));
}
public void UrlTest() throws Exception{
URL url= ServletContextDqpzwj.class.getClassLoader().getResource("main/com/action/servletcfandct/db.properties");
InputStream is=new FileInputStream(url.getPath());
Properties properties = new Properties();
properties.load(is);
System.out.println("驅動類+"+properties.getProperty("db.driver"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}