ServletContext.getRealPath(String str)方法的使用
--------------------------------------------------转载--------------------------------------
由于数据库的配置我想做成配置在一个XML文件里,不过,怎么读取都不成功,,后来我在网上查找,通过下面的方式在servlet获取文件的绝对路径,不过由于多了一个/,还是错误
ServletContext context = getServletContext();
String path = context.getRealPath("/") + "/WEB-INF/drivers.xml";
为了这个我还在另外一个servlet测试了一下,才发现了,呵呵,改成
String path = context.getRealPath("/") + "WEB-INF/drivers.xml";
哈哈一切都搞定了
import javax.servlet.http.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.*;
public void init(ServletConfig config) throws ServletException {
super.init(config);
ServletContext context = getServletContext();
String path = context.getRealPath("/") + "WEB-INF/drivers.xml";
DriverUtilities2.loadDrivers(path);
ConnectionSource.init(getInitParameter("vendor"),
getInitParameter("host"),
getInitParameter("dbName"),
getInitParameter("username"),
getInitParameter("password"));
}
-------------------------------结束------------------------------------------------------
本文介绍了一种在Servlet环境中正确获取XML配置文件绝对路径的方法,解决了因路径配置错误导致的问题,并展示了具体的Java代码实现。
3245

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



