Question

In JSP/JSTL, how can I set values for a usebean of class="java.util.ArrayList".

If I try using c:set property or value, I get the following error: javax.servlet.jsp.JspTagException: Invalid property in : "null"

Was it helpful?

Solution

That isn't directly possible. There are the <c:set> and <jsp:setProperty> tags which allows you to set properties in a fullworthy javabean through a setter method. However, the List interface doesn't have a setter, just an add() method.

A workaround would be to wrap the list in a real javabean like so:

public class ListBean {

    private List<Object> list = new ArrayList<Object>();

    public void setChild(Object object) {
        list.add(object);
    }

    public List<Object> getList() {
        return list;
    }
}

and set it by

<jsp:useBean id="listBean" class="com.example.ListBean" scope="request" />
<jsp:setProperty name="listBean" property="child" value="foo" />
<jsp:setProperty name="listBean" property="child" value="bar" />
<jsp:setProperty name="listBean" property="child" value="waa" />

But that makes little sense. How to solve it rightly depends on the sole functional requirement. If you want to preserve some List upon a GET request, then you should be using a preprocessing servlet. Create a servlet which does the following in doGet() method:

List<String> list = Arrays.asList("foo", "bar", "waa");
request.setAttribute("list", list);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

When you invoke the servlet by its URL, then the list is in the forwarded JSP available by

${list}

without the need for old fashioned <jsp:useBean> tags. In a servlet you've all freedom to write Java code the usual way. This way you can use JSP for pure presentation only without the need to gobble/hack some preprocessing logic by <jsp:useBean> tags.

See also:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top