[英]Reading properties file in Java web application
我目前正在使用ServletContextListener
來設置Web應用程序中JSP的路徑。 這些路徑作為上下文參數存儲在web.xml
,並由偵聽器檢索:
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
sc.setAttribute("urlOfThisPage", sc.getInitParameter("urlOfThisPage"));
sc.setAttribute("urlOfThatPage", sc.getInitParameter("urlOfThatPage"));
在應用程序Servlet中,可以輕松地從ServletContext
檢索特定JSP的路徑。
我的問題與以相同方式處理屬性文件有關。 我在其他StackOverflow頁面(如2161045)上了解了很多。
我是否假定應該由偵聽器讀取屬性文件並使用Property
對象將其存儲在ServletContext
,是否正確? 但是如果是這種情況,我將如何從屬性文件中檢索特定屬性?
目前,我正在Servlet中使用這種代碼來從ServletContext
獲取屬性的值。
String url = (String) sc.getAttribute("urlOfThisPage"); // Use ServletContext to get JSP's URL.
但是我不確定如何將其擴展到訪問屬性文件。
我在ServletContextListener
嘗試了以下方法:
Properties properties = new Properties();
properties.setProperty("name", "Akechi Jinsai");
sc.setAttribute("properties", properties);
在servlet中,使用代碼:
ServletContext sc = request.getSession().getServletContext();
Properties properties = (Properties) sc.getAttribute("properties");
System.out.println("Here: " + properties.getProperty("name"));
顯示“此處:Akechi Jinsai”,但是有沒有一種更好的方式來在servlet中獲取單個屬性而不用這種方式查找內容呢?
只需將屬性文件加載到Servlet中,然后將值移動到HashMap
並將其存儲為應用程序屬性。 現在,使用JavaServer Pages標准標記庫在JSP中訪問它。
在Servlet / JSP中閱讀有關裝入屬性文件的更多信息。
樣例代碼:
JSP :(訪問地圖的不同方法)
<c:forEach items="${map}" var="entry">
Key="${entry.key}" Value=${entry.value}
</c:forEach>
URL Of This Page = ${map.urlOfThisPage }
URL Of That Page = ${map.urlOfThatPage }
URL Of This Page = ${map['urlOfThisPage'] }
URL Of That Page = ${map['urlOfThatPage'] }
的ServletContextListener
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent sc) {
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
// load the properties file if needed
// read the path from web.xml as init parameter
Map<String, String> map = new HashMap<String, String>();
map.put("urlOfThisPage", sc.getInitParameter("urlOfThisPage"));
map.put("urlOfThatPage", sc.getInitParameter("urlOfThatPage"));
sc.setAttribute("map", map);
}
}
web.xml中:
<context-param>
<param-name>urlOfThisPage</param-name>
<param-value>url</param-value>
</context-param>
<context-param>
<param-name>urlOfThatPage</param-name>
<param-value>url</param-value>
</context-param>
<listener>
<listener-class>com.x.y.z.MyServletContextListener</listener-class>
</listener>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.