2011-06-06 114 views
1

從屬性文件創建jsp表(鍵,值)的最佳方式是什麼?使用屬性文件創建jsp表

現在我做這個使用小腳本.....

ResourceBundle statusCodes = ResourceBundle.getBundle("statuscode");  
Enumeration statusKeys = statusCodes.getKeys(); 


    <% 
    while (statusKeys.hasMoreElements()) { 
     String key = (String) statusKeys.nextElement(); 
     String value = statusCodes.getString(key); 
%> 
<tr> 
    <td><%=key%></td> 
    <td><%=value%></td> 
</tr> 

注:有關語法別擔心,這不是完整的代碼。

我怎樣才能做到這一點使用EL和JSTL

回答

2

您應該使用java.util.Properties代替java.util.ResourceBundleResourceBundle提供了一個完全不同的目的,它不應該被濫用來加載屬性的「簡單方法」,因爲它默認從類路徑中查找資源。

servlet加載併爲JSP做好準備。

Properties properties = new Properties(); 
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("/filename.properties")); 
request.setAttribute("properties", properties); 
request.getRequestDispatcher("/WEB-INF/properties.jsp").forward(request, response); 

因爲Properties工具java.util.Map,你可以使用JSTL <c:forEach>遍歷它。每次迭代都會返回Map.Entry,後者又有getKey()getValue()方法。

<table> 
    <c:forEach items="${properties}" var="property"> 
     <tr> 
      <td>${property.key}</td> 
      <td>${property.value}</td> 
     </tr> 
    </c:forEach> 
</table> 

最後通過其URL調用servlet來顯示它。

請注意,ResourceBundle不實施java.util.Map

+0

@BaluC - 謝謝! – user620339 2011-06-07 13:48:07

+0

不客氣。 – BalusC 2011-06-07 13:49:56