将值添加到arraylist使用JSTL

Mic*_*hel 5 java jstl

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

就像是:

<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>    
Run Code Online (Sandbox Code Playgroud)

现在得到错误:

javax.servlet.jsp.JspTagException: Invalid property in &lt;set&gt;:  "null"
Run Code Online (Sandbox Code Playgroud)

谢谢

Bal*_*usC 11

JSTL不是为了做这种事情而设计的.这实际上属于业务逻辑,它直接由servlet类控制.

创建一个类似于的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);
}
Run Code Online (Sandbox Code Playgroud)

将其映射url-pattern/animals.

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

<c:forEach items="${animals}" var="animal">
    ${animal}<br>
</c:forEach>
Run Code Online (Sandbox Code Playgroud)

不需要jsp:useBeanservlet已经设置它.

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

  • @robert:当然可以.只需将该类放入作用域并使用`items ="$ {bean.list}"`其中`$ {bean}'指向具有返回列表的`getList()`方法的类. (2认同)