Java 如何在 JSP/EL 中调用静态方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6395621/
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
How to call a static method in JSP/EL?
提问by John
I'm new to JSP. I tried connecting MySQL and my JSP pages and it works fine. But here is what I needed to do. I have a table attribute called "balance". Retrieve it and use it to calculate a new value called "amount". (I'm not printing "balance").
我是 JSP 的新手。我尝试连接 MySQL 和我的 JSP 页面,它工作正常。但这是我需要做的。我有一个名为“balance”的表属性。检索它并使用它来计算一个名为“amount”的新值。(我不是在打印“余额”)。
<c:forEach var="row" items="${rs.rows}">
ID: ${row.id}<br/>
Passwd: ${row.passwd}<br/>
Amount: <%=Calculate.getAmount(${row.balance})%>
</c:forEach>
It seems it's not possible to insert scriptlets within JSTL tags.
似乎不可能在 JSTL 标记中插入 scriptlet。
采纳答案by BalusC
You cannot invoke static methods directly in EL. EL will only invoke instance methods.
您不能直接在 EL 中调用静态方法。EL 只会调用实例方法。
As to your failing scriptletattempt, you cannot mix scriptletsand EL. Use the one or the other. Since scriptletsare discouragedover a decade, you should stick to an EL-only solution.
至于您失败的scriptlet尝试,您不能混合使用scriptlet和 EL。使用其中之一。由于小脚本被劝阻了十多年,你应该坚持的EL-唯一的解决办法。
You have basically 2 options (assuming both balance
and Calculate#getAmount()
are double
).
您基本上有 2 个选项(假设balance
和Calculate#getAmount()
都是double
)。
Just wrap it in an instance method.
public double getAmount() { return Calculate.getAmount(balance); }
And use it instead:
Amount: ${row.amount}
Or, declare
Calculate#getAmount()
as an EL function. First create a/WEB-INF/functions.tld
file:<?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <display-name>Custom Functions</display-name> <tlib-version>1.0</tlib-version> <uri>http://example.com/functions</uri> <function> <name>calculateAmount</name> <function-class>com.example.Calculate</function-class> <function-signature>double getAmount(double)</function-signature> </function> </taglib>
And use it as follows:
<%@taglib uri="http://example.com/functions" prefix="f" %> ... Amount: ${f:calculateAmount(row.balance)}">
只需将其包装在实例方法中即可。
public double getAmount() { return Calculate.getAmount(balance); }
并改用它:
Amount: ${row.amount}
或者,声明
Calculate#getAmount()
为 EL 函数。首先创建一个/WEB-INF/functions.tld
文件:<?xml version="1.0" encoding="UTF-8" ?> <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <display-name>Custom Functions</display-name> <tlib-version>1.0</tlib-version> <uri>http://example.com/functions</uri> <function> <name>calculateAmount</name> <function-class>com.example.Calculate</function-class> <function-signature>double getAmount(double)</function-signature> </function> </taglib>
并按如下方式使用它:
<%@taglib uri="http://example.com/functions" prefix="f" %> ... Amount: ${f:calculateAmount(row.balance)}">
回答by dma_k
Another approach is to use Spring SpEL:
另一种方法是使用 Spring SpEL:
<%@taglib prefix="s" uri="http://www.springframework.org/tags" %>
<s:eval expression="T(org.company.Calculate).getAmount(row.balance)" var="rowBalance" />
Amount: ${rowBalance}
If you skip optional var="rowBalance"
then <s:eval>
will print the result of the expression to output.
如果跳过可选var="rowBalance"
,然后<s:eval>
将打印的表达,输出的结果。
回答by Lukas
Bean like StaticInterface also can be used
Bean之类的StaticInterface也可以使用
<h:commandButton value="reset settings" action="#{staticinterface.resetSettings}"/>
and bean
和豆
package com.example.common;
import com.example.common.Settings;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean(name = "staticinterface")
@ViewScoped
public class StaticInterface {
public StaticInterface() {
}
public void resetSettings() {
Settings.reset();
}
}
回答by msangel
EL 2.2 has inbuild mechanism of calling methods. More here: oracle site. But it has no access to static methods. Though you can stil call it's via object reference. But i use another solution, described in this article: Calling a Static Method From EL
EL 2.2 具有调用方法的内置机制。更多信息:oracle 网站。但它无法访问静态方法。尽管您仍然可以通过对象引用来调用它。但我使用了本文中描述的另一种解决方案:Calling a Static Method From EL
回答by dhblah
If you're using struts2, you could use
如果您使用的是 struts2,则可以使用
<s:var name='myVar' value="%{@package.prefix.MyClass#myMethod('param')}"/>
and then reference 'myVar' in html or html tag attribute as ${myVar}
然后在 html 或 html 标签属性中引用 'myVar' 作为 ${myVar}
回答by Juan
Based on @Lukas answer you can use that bean and call method by reflection:
根据@Lukas 的回答,您可以使用该 bean 并通过反射调用方法:
@ManagedBean (name = "staticCaller")
@ApplicationScoped
public class StaticCaller {
private static final Logger LOGGER = Logger.getLogger(StaticCaller.class);
/**
* @param clazz
* @param method
* @return
*/
@SuppressWarnings("unchecked")
public <E> E call(String clazz, String method, Object... objs){
final ClassLoader loader = Thread.currentThread().getContextClassLoader();
final List<Class<?>> clasesparamList = new ArrayList<Class<?>>();
final List<Object> objectParamList = new ArrayList<Object>();
if (objs != null && objs.length > 0){
for (final Object obj : objs){
clasesparamList.add(obj.getClass());
objectParamList.add(obj);
}
}
try {
final Class<?> clase = loader.loadClass(clazz);
final Method met = clase.getMethod(method, clasesparamList.toArray(new Class<?>[clasesparamList.size()]));
return (E) met.invoke(null, objectParamList.toArray());
} catch (ClassNotFoundException e) {
LOGGER.error(e.getMessage(), e);
} catch (InvocationTargetException e) {
LOGGER.error(e.getMessage(), e);
} catch (IllegalAccessException e) {
LOGGER.error(e.getMessage(), e);
} catch (IllegalArgumentException e) {
LOGGER.error(e.getMessage(), e);
} catch (NoSuchMethodException e) {
LOGGER.error(e.getMessage(), e);
} catch (SecurityException e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
}
xhtml, into a commandbutton for example:
xhtml,进入一个命令按钮,例如:
<p:commandButton action="#{staticCaller.call('org.company.Calculate', 'getAmount', row.balance)}" process="@this"/>
回答by sendon1982
In Struts2 or Webwork2, you can use this:
在 Struts2 或 Webwork2 中,你可以使用这个:
<s:set name="tourLanguage" value="@foo.bar.TourLanguage@getTour(#name)"/>
Then reference #tourLanguage
in your jsp
然后#tourLanguage
在你的jsp中引用
回答by Sahan Marasinghe
If your Java class is:
如果您的 Java 类是:
package com.test.ejb.util;
public class CommonUtilFunc {
public static String getStatusDesc(String status){
if(status.equals("A")){
return "Active";
}else if(status.equals("I")){
return "Inactive";
}else{
return "Unknown";
}
}
}
Then you can call static method 'getStatusDesc' as below in JSP page.
然后您可以在 JSP 页面中调用静态方法“getStatusDesc”,如下所示。
Use JSTL useBean to get class at top of the JSP page:
使用 JSTL useBean 在 JSP 页面顶部获取类:
<jsp:useBean id="cmnUtilFunc" class="com.test.ejb.util.CommonUtilFunc"/>
Then call function where you required using Expression Language:
然后使用表达式语言在您需要的地方调用函数:
<table>
<td>${cmnUtilFunc.getStatusDesc('A')}</td>
</table>
回答by ash9
<c:forEach var="row" items="${rs.rows}">
ID: ${row.id}<br/>
Passwd: ${row.passwd}<br/>
<c:set var="balance" value="${row.balance}"/>
Amount: <%=Calculate.getAmount(pageContext.getAttribute("balance").toString())%>
</c:forEach>
In this solution, we're assigning value(Through core tag) to a variable and then we're fetching value of that variable in scriplet.
在这个解决方案中,我们将值(通过核心标签)分配给一个变量,然后我们在脚本中获取该变量的值。