Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

java - Add values to arraylist use JSTL

is it possible to add values to an ArrayList instead of using a 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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);
}

Map this on an url-pattern of /animals.

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>

No need for jsp:useBean as servlet has already set it.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...