I have below html and java code to display one row in html table.
<table id="myTable" border="0" cellspacing="0" style="border-spacing:0; width:100%;border-collapse: collapse;">
<%
Object object = request.getAttribute("myContact");
MyModel myModel = (MyModel)object;
String mail = myModel.getmail()!=null ? myModel.getmail().toString().trim() : "";
String title = myModel.gettitle()!=null ? myModel.gettitle().toString().trim() : "";
String name = myModel.getname()!=null ? myModel.getname().toString().trim() : "";
%>
<tr>
<td class="table-border-bottom"><label for="name">Name:</label></td>
<td class="table-border-bottom"><input id="name" type="text" value='<%=name%>' name="name" class="required" style="height: 17px;"/>
</td>
<td class="table-border-bottom"><label for="contactTitle">Title:</label></td>
<td class="table-border-bottom"> <input id="title" type="text" value='<%=title%>' name="title" class="required" style="height: 17px;"/>
</td>
<td class="table-border-bottom"><label for="mail">Email:</label></td>
<td class="table-border-bottom"><input id="mail" type="text" value='<%=mail%>' name="mail" class="required email" style="height: 17px; "/>
</td>
</tr>
<tr align="center">
<td valign="bottom" colspan="6" style="height: 45px; ">
<input type="button" id="submit" name="submit" value="Save" style="width: 80px ; height:24px; text-align: center;border-radius: 10px 10px 10px 10px;"/>
<input type="button" id="revert" name="revert" value="Revert" style="width: 80px ; height:24px;text-align: center;border-radius: 10px 10px 10px 10px;"/></td>
</tr>
</table>
I get one row from the database and keep in request scope then i access the same in jsp and displayed in html table as above. It works well without any issues. Now the problem is i get list of rows from database and i need to display then in html as multiple rows. Also, i have to assign unique ids for each component of the row and also CSS styes need to be applied as above. In such a case how can i repeat above the logic in loop to display list of rows with css styles properly?
Thanks!
Instead, of one single Contact object you would now set a
List<Contact>
instead as a request attribute.Then just use an
Iterator
with awhile
loop.Instead of sending one object from your server code send list of object which you want to display as list of rows.
I have not tested, you please take care of handling null check.
Also, it would be helpful to you by going with JSTL instead of doing with scriptlet.
For styling of rows, apply class like
CSS
If your
MyModel
class has bean style getters like :You should use EL like
${myContact.mail}
to retrieve the value ofmail
attribute.It is even better to use JSTL's
<c:out value="${myContact.mail}">
tag to avoid cross-site scripting.In case you want to display a
List<MyModel>
, set it in therequest
scope in the Servlet which forwards the request to your JSP .Then use , JSTL's
<forEach>
loop to iterate over each element of theList
and display it .Read also :