Reputation: 867
I am trying to create a dynamic table within .jsp
. I have been attempting to do so through scriptlets in the following way (this is pseudocode):
<%
PrintWriter writer = response.getWriter();
writer.println("<table>");
while(records in request object){
writer.println("<tr>" + request.getAttribute().toString() + "</tr>");
}
writer.println("</table");
writer.close();
%>
While the above method can and does work, it is both discouraged, and probably not the best way of accomplishing this task.
To my point and question - is there a better way to create such dynamic content?
Upvotes: 0
Views: 5354
Reputation: 2941
It can be done without scriptlets:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${not empty request.records}">
<table>
<c:forEach items="${request.records}" var="record">
<tr><td> ${record} </td></tr>
</c:forEach>
</table>
</c:if>
Upvotes: 2
Reputation: 6265
You would need to include JSTL dependency on class path, and also configure it in Spring.
If you already have it configured in Spring, then you would create tds dynamically this way:
<table>
<thead>
<tr>
<th>Item1</th>
<th>Item2</th>
<th>Item3</th>
</tr>
</thead>
<tbody>
<c: forEach items="${menus}" var="menu" varStatus="status">
<tr>
<td>${menu.item1}</td>
<td>${menu.item2}</td>
<td>${menu.item3}</td>
</tr>
</c: forEach>
</tbody>
</table >
This ${menus}
is a list coming from backend It is a list of POJO that contains 3 fields item1, item2, and item3.
You would also need to include c name space in your .jsp file: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
There are tons of examples of this on the internet. Just look Spring MVC and JSTL and Table. YOu will find many results.
Upvotes: 1
Reputation: 1266
You can use "out" to print to the response. Why are you doing the first line? Where did you get that?
You could just do the following:
<%
out.println("<table>");
while (records in request object){
out.println("<tr>" + request.getAttribute().toString() + "</tr>");
}
out.println("</table>");
%>
Upvotes: 0