如何在 JSP/EL 中调用静态方法? [英] How to call a static method in JSP/EL?

查看:41
本文介绍了如何在 JSP/EL 中调用静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 JSP 的新手.我尝试连接 MySQL 和我的 JSP 页面,它工作正常.但这是我需要做的.我有一个名为balance"的表属性.检索它并使用它来计算一个名为amount"的新值.(我不是在打印余额").

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

 <c:forEach var="row" items="${rs.rows}">
        ID: ${row.id}<br/>
        Passwd: ${row.passwd}<br/>
        Amount: <%=Calculate.getAmount(${row.balance})%>
 </c:forEach>

似乎无法在 JSTL 标记中插入 scriptlet.

It seems it's not possible to insert scriptlets within JSTL tags.

推荐答案

您不能直接在 EL 中调用静态方法.EL 只会调用实例方法.

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

至于你失败的 scriptlet 尝试,你不能混合 scriptlets 和 EL.使用其中之一.由于scriptlets不鼓励十年,你应该坚持只使用 EL 的解决方案.

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.

您基本上有 2 个选项(假设 balanceCalculate#getAmount() 都是 double).

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

  1. 只需将其包装在实例方法中即可.

  1. Just wrap it in an instance method.

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

改用它:

Amount: ${row.amount}


  • 或者,将 Calculate#getAmount() 声明为 EL 函数.首先创建一个/WEB-INF/functions.tld文件:


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

    并按如下方式使用它:

    <%@taglib uri="http://example.com/functions" prefix="f" %>
    ...
    Amount: ${f:calculateAmount(row.balance)}">
    

  • 这篇关于如何在 JSP/EL 中调用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆