JSTL sql: query variable
I wrote the following code in a JSP file:
<c:catch var="e"> <% int accountNumber = Integer.parseInt(request.getParameter("accountNumber")); int depositAmount = Integer.parseInt(request.getParameter("depositAmount")); %> <sql:query var='account' dataSource="jdbc/bank"> select * from account where AccountNumber=<%= accountNumber %> </sql:query> <c:choose> <c:when test="${account.first() == false}"> <p>Account not found</p> </c:when> <c:otherwise> <h3>Deposit Made</h3> <p>Account number: <%= accountNumber %></p> <p>Deposit amount: <%= depositAmount %></p> <p>New balance: </p> </c:otherwise> </c:choose> </c:catch> <c:if test="${e != null}"> error </c:if>
The problem is that the following code raises javax.el.MethodNotFoundException: the [first] method cannot be found with the exception [0]:
<c:when test="${account.first() == false}"> <p>Account not found</p> </c:when>
I need to access the account variable in sql query: so that I can check if the first row exists.
<sql:query var='account' dataSource="jdbc/bank">
According to the <sql:query>
documentation , account
is a javax.servlet.jsp.jstl.sql.Result
class .
<c:when test="${account.first() == false}">
According to the javadoc class, this class does not have a first()
method. However, there is a getRowCount()
method. I would suggest using this instead.
<c:when test="${account.rowCount == 0}">
Firstly, I highly recommend that you NEVER use scripts . If you rewrote this example as a Java servlet, you would at least check the compilation time, and this will also give you the opportunity to write a JUnit test for logic.
Further, I absolutely hate that they threw <sql>
into the JSTL, which is a blatant disregard for the Model View Controller pattern as you enter the data access code into the interface. This leads to a nightmare for maintenance, so I would rewrite this model code using the Java Persistence API (JPA) or the Hibernate framework.
That said: if you must make this example work, then your problem is that account.first()
not a valid method call. Even if you can return only one result, the query returns a list of results. Try the following:
<c:forEach var="account" begin="0" items="${account.rows}"> <h3>Deposit Made</h3> <p>${account.depositAmount}</p> </c:forEach>
The most reliable way to implement this is to implement a DTO with the first variable, and then the getFirst () method.
public class account { private String first; public String getFirst(){ return first; } .... }
And when you call it in JSP, it should look like this:
test="${!account.first}"
which is called account.getFirst ()
Your SQL data will need to be mapped to this account object in which you will do the entire check, make sure there are no null values, etc.