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>
It seems it's not possible to insert scriptlets within JSTL tags.
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
In the expression ${2 * 2} , the ${} is JSP syntax for interpolating code into HTML.
The jsp scriptlet tag can only declare variables not methods. The jsp declaration tag can declare variables as well as methods. The declaration of scriptlet tag is placed inside the _jspService() method. The declaration of jsp declaration tag is placed outside the _jspService() method.
You cannot invoke static methods directly in EL. EL will only invoke instance methods.
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.
You have basically 2 options (assuming both balance
and Calculate#getAmount()
are double
).
Just wrap it in an instance method.
public double getAmount() { return Calculate.getAmount(balance); }
And use it instead:
Amount: ${row.amount}
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>
And use it as follows:
<%@taglib uri="http://example.com/functions" prefix="f" %> ... Amount: ${f:calculateAmount(row.balance)}">
Another approach is to use Spring SpEL:
<%@taglib prefix="s" uri="http://www.springframework.org/tags" %> <s:eval expression="T(org.company.Calculate).getAmount(row.balance)" var="rowBalance" /> Amount: ${rowBalance}
If you skip optional var="rowBalance"
then <s:eval>
will print the result of the expression to output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With