Home >Java >javaTutorial >How can I invoke static methods in JSP/EL?

How can I invoke static methods in JSP/EL?

Barbara Streisand
Barbara StreisandOriginal
2024-11-20 11:20:02556browse

How can I invoke static methods in JSP/EL?

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:

  1. Create an Instance Method:

    • Create a method within the bean that wraps the static method, passing in the necessary parameters.
    • Use the instance method in EL instead of the static method.
  2. Register a Custom EL Function:

    • Create a tag library descriptor (TLD) file that declares a custom EL function.
    • Configure the TLD file in your JSP page using the <%@taglib...%> directive.
    • Use the custom EL function, which internally invokes the static method, within your EL expression.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn