Calling Static Methods in JSP/EL
In JSP, you often need to perform calculations or access static methods from Java classes. However, invoking static methods directly in Expression Language (EL) is not supported.
Scenario:
You have a table with a "balance" attribute and want to calculate a new value called "amount" using a static method in the "Calculate" class. Scriptlets embedded within JSTL tags, as you have tried, are not recommended.
EL Restriction:
EL can only invoke instance methods on classes that you have created as JavaBeans. Static methods, which are not part of an instance, cannot be directly accessed through EL.
Solutions:
Create an Instance Method:
Register a Custom EL Function:
Example with Instance Method:
public class Bean { private double balance; public double getAmount() { return Calculate.getAmount(balance); } // ...other methods }
<c:forEach var="row" items="${rs.rows}"> Amount: ${row.amount} <!-- Invoke instance method --> </c:forEach>
Example with Custom EL Function:
<!-- functions.tld --> <taglib> ... <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)} <!-- Invoke custom EL function -->
The above is the detailed content of How can I invoke static methods in JSP/EL?. For more information, please follow other related articles on the PHP Chinese website!