java JSP从servlet获取变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16906668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSP get variable from servlet
提问by saahs
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
servlet 方法 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
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?
还有我的第二个问题。当我有几个动态文本框时,我需要它们在 servlet 中的值。我可以将它们组合成 jsp 文件中的字符串,然后向 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>
回答by Luiggi Mendoza
The problem is that you're using request.getParameter
in ankieta.jspwhen you have set an attribute. Change it for request.getAttribute
:
问题是您在设置属性时request.getParameter
在ankieta.jsp 中使用。将其更改为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?
现在,如果您正处于学习阶段,我强烈建议您停止使用 scriplets。这在这里有大量解释:如何避免 JSP 文件中的 Java 代码?
Using EL and JSTL, the code in your JSP would be:
使用 EL 和 JSTL,您的 JSP 中的代码将是:
<c:forEach var="i" begin="0" end="${a}">
Number: ${i} <br />
</c:forEach>