📄 querytag.java
字号:
package examples;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;import java.io.*;import java.sql.*;import java.sql.Connection;/** * A query tag. * * Make a query using a connection. Either use the connection from * the enclosing connection tag, or from a connection attribute that points * into a PageContext entry * * (A) Either * <connection id="con01" ....> ... </connection> * <query id="balances" connection="con01"> * SELECT account, balance FROM acct_table * where customer_number = <%=request.custno %> * </query> * * (B) Or * <connection ...> * <query id="balances"> * SELECT account, balance FROM acct_table * where customer_number = <%=request.custno %> * </query> * </connection> * * For this example, unlike connection, we will require an id. * * All JDBC code is pretty much faked */public class QueryTag extends BodyTagSupport { /** * Create a new QueryTag */ public QueryTag() { super(); } /** * Attributes for this action: * id (inherited) * connection */ /** * Connection: the id of the connection object * Setter and getter methods */ public void setConnection(String s) { connectionId = s; } public String getConnection() { return connectionId; } /** * process the start Tag * Get attributes, locate any objects that are required to be in * the pagecontext. * * @return evaluate the body */ public int doStartTag() throws JspTagException { String cid = getConnection(); if (cid != null) { // there is a connection id, use it connection = (Connection) pageContext.getAttribute(cid); } else { ConnectionTag tag = (ConnectionTag) findAncestorWithClass(this, ConnectionTag.class); if (tag == null) { throw new JspTagException("a query without a connection attribute must be nested within a ConnectionTag tag"); } connection = tag.getConnection(); } if (connection == null) { throw new JspTagException("could not find connection object"); } return EVAL_BODY_TAG; } /** * Process after body evaluation * Extract the String from the nested stream; do a query; * save away the value into a field instance. * * @return whether the body should be reevaluated */ public int doAfterBody() throws JspTagException { BodyContent body = getBodyContent(); // get the body as string String query = body.getString(); // clean up body.clearBody(); try { Statement stmt = connection.createStatement(); result = stmt.executeQuery(query); } catch (SQLException ex) { throw new JspTagException("trouble in execution"); } return SKIP_BODY; } /** * End, create the object */ public int doEndTag() { pageContext.setAttribute(getId(), result); return EVAL_PAGE; } // variables private ResultSet result; // the JDBC result set private Connection connection; // the JDBC connection object private String connectionId; // the connection attribute}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -