简体   繁体   English

如何在Servlet类中使用for循环?

[英]How do i use a for loop in a servlet class?

I have an index file and a servlet class file. 我有一个索引文件和一个servlet类文件。 I need to create a table after i submit information from the index to the servlet class. 在将索引中的信息提交到Servlet类后,需要创建一个表。 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. 该信息作为数字传递给servlet。 I need to make tables with the number. 我需要用数字做表格。 If it is 1, it is 1 row, if iti s 5 it is 5 rows. 如果为1,则为1行;如果为5,则为5行。 I need to use a for loop on the servlet page, but i am stuck. 我需要在servlet页面上使用for循环,但是我被卡住了。 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. 尽量避免使用Scriplets。 You can use forEach JSTL tag for looping in jsp file itself. 您可以使用forEach JSTL标记来循环jsp文件本身。

set the count as request attribute in the servlet and then access it in jsp as shown below: 在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>

Read How to loop over something a specified number of times in JSTL? 阅读如何在JSTL中循环指定次数的内容?

Complete example: 完整的例子:

HTML: HTML:

<form name="form" method="post" action="servlet">
    Number: <input type="number" name="table"/>
    <input type="submit" value="Submit"/>
 </form> 

Servlet 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: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM