How to add values to an ArrayList referenced by jsp:useBean?

老子叫甜甜 提交于 2019-11-26 21:58:45

问题


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"


回答1:


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:

  • Our servlets wiki page


来源:https://stackoverflow.com/questions/6024435/how-to-add-values-to-an-arraylist-referenced-by-jspusebean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!