Java JSTL、Beans 和方法调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/227500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:44:56  来源:igfitidea点击:

JSTL, Beans, and method calls

javaexceptionjspjstlvignette

提问by Zack The Human

I'm working on a JSP where I need to call methods on object that come from a Bean. The previous version of the page does not use JSTL and it works properly. My new version has a set up like this:

我正在开发一个 JSP,我需要在来自 Bean 的对象上调用方法。以前版本的页面没有使用 JSTL 并且可以正常工作。我的新版本有这样的设置:

<jsp:useBean id="pageBean" scope="request" type="com.epicentric.page.website.PageBean" />
<c:set var="pageDividers" value="<%= pageBean.getPageDividers() %>" />
<c:set var="numColumns" value="${pageDividers.size()}" />

The variable pageDividersis a Listobject.

变量pageDividers是一个List对象。

I'm encountering this issue: when I ask for pageDivider's size, an exception is thrown. I know this is a simple JTSL error -- what am I doing wrong?

我遇到了这个问题:当我询问pageDivider的大小时,会抛出异常。我知道这是一个简单的 JTSL 错误——我做错了什么?

The error message is:

错误信息是:

The function size must be used with a prefix when a default namespace is not specified

当未指定默认命名空间时,函数大小必须与前缀一起使用

How do I correctly access or call the methods of my pageDividersobject?

如何正确访问或调用pageDividers对象的方法?

采纳答案by abahgat

When using the dot operator for property access in JSTL, ${pageDividers.size}(no ()needed) results in a call to a method named getSize().
Since java.util.List offers a method called size()(rather than getSize()) you won't be able to access the list length by using that code.

在 JSTL 中使用点运算符进行属性访问时,${pageDividers.size}(不需要())会导致调用名为 的方法getSize()
由于 java.util.List 提供了一种称为size()(而不是getSize())的方法,因此您将无法使用该代码访问列表长度。



In order to access to a list size, JSTL offers the fn:lengthfunction, used like

为了访问列表大小,JSTL 提供了fn:length函数,像这样使用

${fn:length(pageDividers)}

Note that in order to use the fnnamespace, you should declare it as follows

请注意,为了使用fn命名空间,您应该将其声明如下

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

In addition, the same function can be used with any collection type, and with Strings too.

此外,相同的函数可以用于任何集合类型,也可以用于字符串。

回答by Vincent Ramdhanie

To access the property of a bean using EL you simply name the property (not invoke the method). So lets say you have a method called getSize() in the bean then

要使用 EL 访问 bean 的属性,您只需命名该属性(而不是调用该方法)。因此,假设您在 bean 中有一个名为 getSize() 的方法,然后

${pageDividers.size}

Notice no ().

注意没有()。

EDIT:Sorry...made an error in the original post.

编辑:对不起......在原始帖子中犯了一个错误。