create a jsp table using properties file
What is the best possible way to create a jsp table(key,value) from a properties file.
Right now I am doing this using scriptlets.....
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>
NOTE: Dont worry about syntax this is not compl开发者_JS百科ete code.
How can I do this using EL and jstl
You should be using java.util.Properties
instead of java.util.ResourceBundle
. The ResourceBundle
serves an entirely different purpose and it should not be abused to have "an easy way" to load properties since it by default lookups resources from the classpath.
Let a servlet load and prepare it for 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);
Because Properties
implements java.util.Map
, you can just use JSTL <c:forEach>
to iterate over it. Every iteration gives a Map.Entry
back which in turn has getKey()
and getValue()
methods.
<table>
<c:forEach items="${properties}" var="property">
<tr>
<td>${property.key}</td>
<td>${property.value}</td>
</tr>
</c:forEach>
</table>
Finally invoke the servlet by its URL to get it to display.
Please note that ResourceBundle
doesn't implement java.util.Map
!
精彩评论