java 从 JSP 中的数组输出字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2733531/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:36:16  来源:igfitidea点击:

Output a String from an array in JSP

javajspjavabeans

提问by Sandeep Bansal

I want to make a quiz, I want to have to output an array of questions after a form is submitted.

我想做一个测验,我想在提交表单后输出一系列问题。

I know to use a bean I think but how would I do this?

我知道使用我认为的豆子,但我该怎么做呢?

Thanks

谢谢

采纳答案by BalusC

Use the JSTL<c:forEach>for this. JSTL support is dependent on the servletcontainer in question. For example Tomcatdoesn't ship with JSTL out of the box. You can install JSTL by just dropping jstl-1.2.jarin /WEB-INF/libof your webapplication. You can use the JSTL core tagsin your JSP by declaring it as per its documentation in top of your JSP file:

为此使用JSTL<c:forEach>。JSTL 支持取决于所讨论的 servletcontainer。例如,Tomcat不附带开箱即用的 JSTL。您可以通过将jstl-1.2.jar放入/WEB-INF/lib您的 web 应用程序中来安装 JSTL 。您可以在 JSP 中使用JSTL 核心标记,方法是根据 JSP 文件顶部的文档对其进行声明:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

You can locate an array (Object[]) or Listin the itemsattribute of the <c:forEach>tag. You can define each item using the varattribute so that you can access it inside the loop:

您可以定位一个数组 ( Object[]) 或List在标签的items属性中<c:forEach>。您可以使用var属性定义每个项目,以便您可以在循环内访问它:

<c:forEach items="${questions}" var="question">
    <p>Question: ${question}</p>
</c:forEach>

This does basically the same as the following in plain Java:

这与普通 Java 中的以下内容基本相同:

for (String question : questions) { // Assuming questions is a String[].
    System.out.println("<p>Question: " + question + "</p>");
}

回答by Rob Tanzola

With JSP 2.0, it might look something like this:

使用 JSP 2.0,它可能看起来像这样:

<% 
request.setAttribute( "questions", new String[]{"one","two","three"} );  
%>   
<c:forEach var="question" items="${questions}" varStatus="loop">  
    [${loop.index}]: ${question}<br/>  
</c:forEach>  

where questions would be set in the code that handles the submit instead of in the JSP.

在处理提交的代码中而不是在 JSP 中设置问题。

If you are using JSP 1.2:

如果您使用的是 JSP 1.2:

<c:forEach var="question" items="${questions}" varStatus="loop">  
    <c:out value="[${loop.index}]" />: <c:out value="${question}"/><br/>  
</c:forEach>  

Using EL and JSTL you will be able to access any Question object properties if you are storing objects in the array instead of just Strings:

如果您将对象存储在数组中,而不仅仅是字符串,则使用 E​​L 和 JSTL,您将能够访问任何 Question 对象属性:

${question.myProperty}