0

I have two problems,

First:

Form

<FORM ACTION="create" METHOD="POST">
<fieldset>
<INPUT TYPE="TEXT" NAME="paraile">
<input type="submit" name="Submit" class="button" value="Gen" />
</fieldset>
</FORM>

servlet method doPost

String ankieta = "WEB-INF/ankieta.jsp";

int ile = Integer.parseInt(request.getParameter("paraile"));
request.setAttribute("ile", ile);
request.getRequestDispatcher(ankieta).forward(request, response);

ankieta.jsp

  <%
  int a= Integer.parseInt(request.getParameter("ile"));
      for (int i = 0; i < a; i++) {
  %>
         Number: <%=i%> 
  <%
      } 
  %>

This simple excercise doesn't work. Really, I need loop to create a couple textbox to voting.

and my second question. When I have a few dynamic textbox, and I need their value in servlet. Can I combine them to string in jsp file and then send one parameter to servlet?

edit: It's working, but still this is badly solution. Thank You Luiggi!

<FORM ACTION="create" METHOD="POST">
<fieldset>
<legend>Vote</legend>
<%
  String string = (String) request.getAttribute("ile");
  int a= Integer.parseInt(string);
  for (int i=1; i <= a; ++i) {
%>
    <label>Option <%=i%></label>
    <INPUT TYPE="TEXT" NAME="option<%=i%>"> 
<%
  } 
%>

<input type="submit" name="Submit" class="button" value="Accept" />
</fieldset>
4

1 回答 1

7

The problem is that you're using request.getParameter in ankieta.jsp when you have set an attribute. Change it for request.getAttribute:

int a= Integer.parseInt(request.getParameter("ile"));

Now, if you're in learning phase, I strongly recommend to stop using scriplets. This is heavily explained here: How to avoid Java code in JSP files?

Using EL and JSTL, the code in your JSP would be:

<c:forEach var="i" begin="0" end="${a}">
    Number: ${i} <br />
</c:forEach>
于 2013-06-03T22:10:38.477 回答