Reputation: 306
Good evening, I am trying to display the output of a HashTable inside a HTML <table>
instead of using System.out.print
. The problem is, I do not know the exact way to do it. I tried several methods but I still do not understand the logic on how to do it. I tried something like this:
Sample Code
public void printHtmlData() {
Hashtable htmlData = new Hashtable();
.....
.....
Enumeration enumeration = htmlData.elements();
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}
}
The output with System.out.print
[I|desperately, need, a, girl, haru, haru, big, bang, the, best]
[I|123, 456, a, girl, haru, haru, big, bang, the, best]
[I|desperately, need, 789, 000, haru, haru, big, bang, the, best]
[I|desperately, need, a, girl, just, a, sample, output, for, testing]
I tried to do this for the html output in another jsp file
<jsp:useBean ....."/>
Hashtable printHtml = new Hashtable();
<TABLE width="100%" style="border-width : 2px 0px 0px 0px;border-style : solid solid solid solid;border-color : #C0C0C0 #C0C0C0 #C0C0C0 #C0C0C0;">
<TR>
<TD><%
printHtml.printHtmlData();
%></TD>
</TR>
</TABLE>
I need some hints, thanks...
Upvotes: 0
Views: 330
Reputation: 6568
From your comments, I'm thinking that you do not know JSTL yet. Ravi Thapliyal answer is the right way to go about this by separating the business logic and the presentation. Check out Model View Controller for more info. Anyway since you are using scriplets, you could simply move the logic inside the HTML then use the implicit out
object to display your content (again, keep in mind that this is not a good approach if you try to mix business logic with presentation). You can use the pseudocode below as a guide. Fix the HTML as needed if you want to format a certain way. And yes, do consider using a HashMap instead if synchronization is not an issue for you. You can start here for starters.
Differences between HashMap and Hashtable?
Pseudocode
<table>
<tr>
<% while (enumeration.hasMoreElements()) { %>
<td><%= enumeration.nextElement() %></td>
<%}%>
</tr>
</table>
Upvotes: 0
Reputation: 51711
The correct approach would be to have a servlet populate the HttpServletRequest
with your model, the HashTable
, and forwarding it to your JSP. (Also, consider using a HashMap
instead.)
Within a Servlet:
Hashtable nonHtmlData = new Hashtable();
// populate the map; set as request attr
request.setAttribute("model", nonHtmlData);
// forward to JSP
RequestDispatcher view = request.getRequestDispatcher("display.jsp");
view.forward(request, response);
Then within your JSP using EL and JSTL tags:
<table>
<c:forEach var="list" items="${model}">
<tr>
<th>${list.key}</th>
<c:forEach var="listItem" items="${list.value}">
<td>${listItem}</td>
</c:forEach>
</tr>
</c:forEach>
</table>
Upvotes: 1