I have an index file and a servlet class file. I need to create a table after i submit information from the index to the servlet class. I submit the form.
<form name="form" method="post" action="servlet">
Number: <input type="number" name="table"/>
<input type="submit" value="Submit"/>
</form>
This information is passed to the servlet as a number. I need to make tables with the number. If it is 1, it is 1 row, if iti s 5 it is 5 rows. I need to use a for loop on the servlet page, but i am stuck. I have tried something like below, but it does not work.
<table>
<% for(int row=1; row <= 5; row++) { %>
<tr>
</tr>
<% } %>
</table>
Try to avoid Scriplets. You can use forEach JSTL tag for looping in jsp file itself.
set the count
as request attribute in the servlet and then access it in jsp as shown below:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<c:forEach begin="0" end="${count}" varStatus="loop">
Index: ${loop.index}<br/>
</c:forEach>
Read How to loop over something a specified number of times in JSTL?
Complete example:
HTML:
<form name="form" method="post" action="servlet">
Number: <input type="number" name="table"/>
<input type="submit" value="Submit"/>
</form>
Servlet
//inside doPost method
request.setAttribute("count", request.getParameter("table");
// redirect to jsp
String nextJSP = "/table.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
JSP:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<c:forEach begin="0" end="${count}" varStatus="loop">
Index: ${loop.index}<br/>
</c:forEach>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.