本文介绍了如何在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个选择(假设两个余额计算#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}





  • 或者,声明计算#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中调用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    1403页,肝出来的..

    09-07 01:38