如何在 JSP/EL 中调用静态方法?

我刚来 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>

在 JSTL 标记中插入 scriptlet 似乎是不可能的。

97180 次浏览

You cannot invoke static methods directly in EL. EL will only invoke instance methods.

As to your failing scriptlet attempt, you cannot mix scriptlets and EL. Use the one or the other. Since scriptlets are discouraged over a decade, you should stick to an EL-only solution.

You have basically 2 options (assuming both balance and Calculate#getAmount() are double).

  1. Just wrap it in an instance method.

    public double getAmount() {
    return Calculate.getAmount(balance);
    }
    

    And use it instead:

    Amount: ${row.amount}
    

  2. 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)}">
    

Another approach is to use 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.

Bean like StaticInterface also can be used

<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();
}
}

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

If you're using struts2, you could use

<s:var name='myVar' value="%{@package.prefix.MyClass#myMethod('param')}"/>

and then reference 'myVar' in html or html tag attribute as ${myVar}

Based on @Lukas answer you can use that bean and call method by reflection:

@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:

<p:commandButton action="#{staticCaller.call('org.company.Calculate', 'getAmount', row.balance)}" process="@this"/>

In Struts2 or Webwork2, you can use this:

<s:set name="tourLanguage" value="@foo.bar.TourLanguage@getTour(#name)"/>

Then reference #tourLanguage in your jsp

If your Java class is:

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.

Use JSTL useBean to get class at top of the JSP page:

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