2013-07-17 50 views
1

我其实有PROGRAMM与servlet:Servlet的init和

@WebServlet("/Controler") 
public class Controler extends HttpServlet { 

} 

我需要使用属性文件:file.properties在我的计划。加载它,我有一个类:

public class PropLoader { 

    private final static String m_propertyFileName = "file.properties"; 

    public static String getProperty(String a_key){ 

     String l_value = ""; 

     Properties l_properties = new Properties(); 
     FileInputStream l_input; 
     try { 

      l_input = new FileInputStream(m_propertyFileName); // File not found exception 
      l_properties.load(l_input); 

      l_value = l_properties.getProperty(a_key); 

      l_input.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return l_value; 

    } 

} 

我的属性文件是在WebContent文件夹,我可以访问它:

String path = getServletContext().getRealPath("/file.properties"); 

但我不能调用其他类论文的方法比servlet ...

我如何访问PropLoader类中的属性文件?

+0

好吧,一种选择是将路径作为静态变量添加到PropLoader类(单类的一种)。我已经看到了一些主要servlet在init()方法中执行这些步骤的情况,因此您将在整个应用程序中提供您的路径。你只需要确定你正在处理的servlet是在应用程序启动时加载的。 – Martin

+0

我试过这个解决方案,但servlet无法在propLoader类中实例化路径,我认为这是由于init()servlet方法 – Apaachee

回答

2

如果你想从Web应用程序结构中读取文件,那么你应该使用ServletContext.getResourceAsStream()。当然,既然你从webapp加载它,你需要引用表示webapp的对象:ServletContext。你可以在你的servlet覆盖init(),称getServletConfig().getServletContext()得到这样的引用,并通过servlet上下文的方法加载该文件:

@WebServlet("/Controler") 
public class Controler extends HttpServlet { 
    private Properties properties; 

    @Override 
    public void init() { 
     properties = PropLoader.load(getServletConfig().getServletContext()); 
    } 
} 

public class PropLoader { 

    private final static String FILE_PATH = "/file.properties"; 

    public static Properties load(ServletContext context) { 
     Properties properties = new Properties(); 
     properties.load(context.getResourceAsStream(FILE_PATH)); 
     return properties; 
    } 
}  

注意某些异常必须进行处理。

另一种解决方案是将文件置于WEB-INF/classes的部署webapp中,并使用ClassLoader加载文件:getClass().getResourceAsStream("/file.properties")。这样,你不需要参考ServletContext

+0

嗨JB Nizet!对于第二种解决方案,我将我告诉的结果复制/粘贴到Icestari:我的属性文件位于Eclipse WebContent根文件夹中,'in == null'中包含:InputStream in = Controler.class.getClassLoader()。的getResourceAsStream(m_propertyFileName); '那么,我不确定要理解你的第一个解决方案 – Apaachee

+0

这就是为什么我的回答告诉你,为了使这个解决方案起作用,文件必须在WEB-INF/classes下。我会编辑我的答案,使第一部分更清晰。 –

+0

与我的属性文件的结果相同:'WEB-INF/classes/file.properties'或'WEB-INF/file.properties',getResourceAsStream()返回null。 – Apaachee

1

我会推荐使用getResourceAsStream方法(下面的例子)。它需要属性文件位于WAR类路径中。

InputStream in = YourServlet.class.getClassLoader().getResourceAsStream(path_and_name); 

问候 栾

+0

感谢您的回答Icestari!我的属性文件位于Eclipse WebContent根文件夹中,'in == null'中有:'InputStream in = Controler.class.getClassLoader()。getResourceAsStream(m_propertyFileName);' – Apaachee

相关问题