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

How can I invoke static methods in JSP/EL?

Barbara Streisand
Release: 2024-11-20 11:20:02
Original
555 people have browsed it

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
}
Copy after login
<c:forEach var="row" items="${rs.rows}">
    Amount: ${row.amount}  <!-- Invoke instance method -->
</c:forEach>
Copy after login

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>
Copy after login
<%@taglib uri="http://example.com/functions" prefix="f"%>
...
Amount: ${f:calculateAmount(row.balance)}  <!-- Invoke custom EL function -->
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template