Java 使用 JSTL 将值添加到 arraylist

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

Add values to arraylist use JSTL

javajstl

提问by Michel

is it possible to add values to an ArrayList instead of using a HashMap

是否可以将值添加到 ArrayList 而不是使用 HashMap

something like:

就像是:

<jsp:useBean id="animalList" class="java.util.ArrayList" />

<c:set target="${animalList}" value="Sylvester"/>

<c:set target="${animalList}" value="Goofy"/>

<c:set target="${animalList}" value="Mickey"/>

<c:forEach items="${animalList}" var="animal">

${animal}<br>

</c:forEach>    

now getting the error:

现在收到错误:

javax.servlet.jsp.JspTagException: Invalid property in &lt;set&gt;:  "null"

thx

谢谢

采纳答案by BalusC

JSTL is not designed to do this kind of stuff. This really belongs in the business logic which is (in)directly to be controlled by a servlet class.

JSTL 不是为做这种事情而设计的。这确实属于业务逻辑,它(in)直接由 servlet 类控制。

Create a servlet which does like:

创建一个像下面这样的 servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    List<String> animals = new ArrayList<String>();
    animals.add("Sylvester");
    animals.add("Goofy");
    animals.add("Mickey");
    request.setAttribute("animals", animals);
    request.getRequestDispatcher("/WEB-INF/animals.jsp").forward(request, response);
}

Map this on an url-patternof /animals.

将此映射url-pattern/animals

Now create a JSP file in /WEB-INF/animals.jsp(place it in WEB-INFto prevent direct access):

现在创建一个 JSP 文件/WEB-INF/animals.jsp(将其放入WEB-INF以防止直接访问):

<c:forEach items="${animals}" var="animal">
    ${animal}<br>
</c:forEach>

No need for jsp:useBeanas servlet has already set it.

不需要,jsp:useBean因为 servlet 已经设置了它。

Now call the servlet+JSP by http://example.com/context/animals.

现在通过 调用servlet+JSP http://example.com/context/animals

回答by Sarvesh

The above code is not working.

上面的代码不起作用。

Following are the lines of code that has to be placed in file animals.jsp

以下是必须放在文件中的代码行 animals.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:forEach var="animal" items="${animals}">
   <c:set var="animalName" value="${animal}"/>
   <c:out value="${animalName}"/>
</c:forEach>

回答by Marcos Gomes

To do add() to a List or others methods from Map, Set, etc... You have to use a unusable variable.

要从 Map、Set 等对 List 或其他方法执行 add() 操作...您必须使用不可用的变量。

<jsp:useBean id="list" class="java.util.ArrayList"/> <c:set var="noUse" value="${list.add('YourThing')}"/> <c:out value=${list} />

<jsp:useBean id="list" class="java.util.ArrayList"/> <c:set var="noUse" value="${list.add('YourThing')}"/> <c:out value=${list} />