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