问题描述
在 JSP/JSTL 中,如何为 class="java.util.ArrayList" 的 usebean 设置值.
In JSP/JSTL, how can I set values for a usebean of class="java.util.ArrayList".
如果我尝试使用 c:set 属性或值,我会收到以下错误:javax.servlet.jsp.JspTagException: Invalid property in : "null"
If I try using c:set property or value, I get the following error:javax.servlet.jsp.JspTagException: Invalid property in : "null"
推荐答案
这不是直接可能的.有 和
标签,它们允许您通过 setter 方法在完整的 javabean 中设置属性.但是,
List
接口没有 setter,只有一个 add()
方法.
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.
解决方法是将列表包装在真正的 javabean 中,如下所示:
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;
}
}
并设置它
<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" />
但这没什么意义.如何正确解决它取决于唯一的功能需求.如果您想在 GET 请求时保留一些 List
,那么您应该使用预处理 servlet.创建一个 servlet,它在 doGet()
方法中执行以下操作:
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);
当您通过 URL 调用 servlet 时,该列表位于转发的 JSP 中
When you invoke the servlet by its URL, then the list is in the forwarded JSP available by
${list}
不需要老式的标签.在 servlet 中,您可以按照通常的方式自由地编写 Java 代码.通过这种方式,您可以仅将 JSP 用于纯粹的演示,而无需通过
标签吞噬/破解一些预处理逻辑.
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.
这篇关于如何向 jsp:useBean 引用的 ArrayList 添加值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!