我正在使用Tomcat.我想把配置文件放在WEB-INF默认的根类路径中,而不是默认的根类路径WEB-INF/classes.目前,我把config.xml在WEB-INF和使用以下相对地址找到它:
InputStream input = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("..//config.xml");
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?
或者我应该使用第getServletContext().getRealPath("config.xml")一个?但我不知道如何获得getServletContext()一个.java.(我试图new HttpServlet获得getServletContext(),但因为它是一个抽象类,不能实例化......我怎么能得到getServletContext()?)
该方法getRealPath()无法保证工作,例如,如果您的webapp未从war文件扩展,则文件系统上没有"真实路径"到war文件中的文件.
既然你说你正在使用ServletContextListener,你可以从ServletContextEvent中获取ServletContext:
sce.getServletContext().getResourceAsStream("/WEB-INF/config.xml");
Run Code Online (Sandbox Code Playgroud)