How does jstl sql tag work?

I am using the following code to query a database from my jsp, but I would like to know more about what happens behind the scenes.

These are my two main questions.

Is the tag directly accessing the ResultSet or is the query result stored in a data structure in memory?

When is the connection closed?

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

<sql:query var="query" dataSource="${ds}" sql="${listQuery}"></sql:query>
<c:forEach var="row" items="${query.rows}" begin="0">
    ${row.data }
    ${row.more_data }
</c:forEach>

Note. I have always opposed running queries in jsp, but my result set is too large to hold in memory between my action and my jsp. Using this tag library looks like the easiest solution.

+3
source share
2 answers

Source Based Cases for org.apache.taglibs.standard.tag.common.sql.QueryTagSupport

lib ResultSet , . , , .

, ( doStartTag). , ( doEndTag). doFinally.

, .

+8

: javax.servlet.jsp.jstl.sql.Result

JSTL SQL Query. , :

public java.util.SortedMap [] getRows()

c: forEach "" javax.servlet.jsp.jstl.sql.Result, Result - , (, , ..).

, , SQL- .

JSP, , , SQL .

, .

"" Iterator, "" ResultSet. , (, forEach). .

public class ResultSetIterator implements Iterator {

Connection con;
Statement s;
ResultSet rs;
Object curObject;
boolean closed;

public ResultSetIterator(Connection con, Statement s, ResultSet rs) {
    this.con = con;
    this.s = s;
    this.rs = rs;
    closed = false;
}

public boolean hasNext() {
    advance();
    return curObject != null;
}

public Object next() {
    advance();
    if (curObject == null) {
        throw new NoSuchElementException();
    } else {
        Object result = curObject;
        curObject = null;
        return result;
    }
}

public void remove() {
    throw new UnsupportedOperationException("Not supported yet.");
}

private void advance() {
    if (closed) {
        curObject = null;
        return;
    }
    if (curObject == null) {
        try {
            if (rs.next()) {
                curObject = bindObject(rs);
            }
        } catch (SQLException ex) {
            shutDown();
            throw new RuntimeException(ex);
        }
    }
    if (curObject == null) {
        // Still no object, must be at the end of the result set
        shutDown();
    }
}

protected Object bindObject(ResultSet rs) throws SQLException {
    // Bind result set row to an object, replace or override this method
    String name = rs.getString(1);
    return name;
}

public void shutDown() {
    closed = true;
    try {
        rs.close();
    } catch (SQLException ex) {
        // Ignored
    }
    try {
        s.close();
    } catch (SQLException ex) {
        // Ignored
    }
    try {
        con.close();
    } catch (SQLException ex) {
        // Ignored
    }
}

} >

, , . JSTLs forEach Iterator, , . . ( , , , , Iterator ResultSets.)

+1

Source: https://habr.com/ru/post/1697148/


All Articles