使用JSTL向arraylist添加值
是否可以将值添加到ArrayList而不是使用HashMap
is it possible to add values to an ArrayList instead of using a 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>
现在出现错误:
javax.servlet.jsp.JspTagException: Invalid property in <set>: "null"
thx
JSTL并非旨在执行此类操作.这确实属于业务逻辑,该业务逻辑将(间接)由Servlet类控制.
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.
创建一个如下所示的servlet:
Create a servlet which does like:
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);
}
将此映射到/animals
的url-pattern
.
现在在/WEB-INF/animals.jsp
中创建一个JSP文件(将其放置在WEB-INF
中以防止直接访问):
Now create a JSP file in /WEB-INF/animals.jsp
(place it in WEB-INF
to prevent direct access):
<c:forEach items="${animals}" var="animal">
${animal}<br>
</c:forEach>
不需要jsp:useBean
,因为servlet已经设置了它.
No need for jsp:useBean
as servlet has already set it.
现在通过http://example.com/context/animals
调用servlet + JSP.
Now call the servlet+JSP by http://example.com/context/animals
.