有时候我们需要利用遍历的方法动态生成指定数量的文本框,如
<c:forEach var="sqltest" items="${list}">
<tr>
<td>${sqltest.question_id}、${sqltest.question}</td>
<td>
<div class="row cl">
<div class="formControls col-xs-8">
<input id="" name="${sqltest.question_id }" type="text" placeholder="请输入答案" class="input-text size-L">
</div>
</div>
</td>
</tr>
</c:forEach>
这个文本框是通过遍历实现的,这样子就实现了前台的动态生成,但是也才出现了一个较为严重的问题,在jsp传给servlet中,传值的判断对象是name属性,也就是上面代码中的${sqltest.question_id }。而在后台接受中,是采用request.getParameter(“name”)的方式进行接受的,如何实现这一操作呢?
在这里就介绍一种我摸索到的方法,在前台是利用遍历生成的表达式时并且是需要传值给后台的时候,最好将name的值和数字关联。如上面的代码将修改第7行的代码。
<input id="" name="question${sqltest.question_id }" type="text" placeholder="请输入答案" class="input-text size-L">
我的代码中是用EL表达式,${sqltest.question_id}的显示内容是数字,如上面的代码在网页的值实际上是name=“question1”。这么做一是将它和数字关联起来,第二个是因为考虑到getParameter的特殊性质,在后台中无法采用String s = "1";request.getParameter(s)的方法取值,因为请求会自动默认为s字段,寻找前台文本内容中name属性是“s”的文本内容,而不是前台中文本框的name属性是“1”的内容。
后台的代码实现需要将两个String类型的参数组合。
int i = 1;
String x = String.valueOf(i);
String name = "question";
String question = request.getParameter(name + x);
System.out.println(question +" " + name + x);
通过这样就能解决获取前台的遍历生成的文本的值。