我有一个索引文件和一个 servlet 类文件。将索引中的信息提交到 servlet 类后,我需要创建一个表。我提交表格。
<form name="form" method="post" action="servlet">
Number: <input type="number" name="table"/>
<input type="submit" value="Submit"/>
</form>
此信息作为数字传递到 servlet。我需要用数字制作表格。如果为 1,则为 1 行,如果为 5,则为 5 行。我需要在 servlet 页面上使用 for 循环,但我陷入困境。我已经尝试过类似下面的方法,但它不起作用。
<table>
<% for(int row=1; row <= 5; row++) { %>
<tr>
</tr>
<% } %>
</table>
最佳答案
尽量避免 Scriplet。您可以使用forEach用于在 jsp 文件本身中循环的 JSTL 标记。
在servlet中将count
设置为request属性,然后在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>
阅读How to loop over something a specified number of times in JSTL?
完整示例:
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>
关于java - 如何在 servlet 类中使用 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33295128/