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

前端 未结 1 876
闹比i
闹比i 2020-12-06 23:39

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.js

相关标签:
1条回答
  • 2020-12-07 00:00

    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
    0 讨论(0)
提交回复
热议问题