⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tag-connection.xtp

📁 解压在c盘
💻 XTP
字号:
<s1 title="Connection Tag"><p>The connection tag provides a robust way for a JSP page to get adatabase connection without getting tangled up in the APIs to makethat work.</p><p>The JSP 1.2 TryCatchFinally interface lets tag library designers createmore robust libraries.  For example, database connections must alwaysbe closed, even when exceptions occur.  The TryCatchFinally interfacelets a ConnectionTag automatically close the connection when the tagcompletes.</p><p>The connection tag example creates a JSP tag to look up a databasedata source in the environment using JNDI.  From that data source, itcreates a new connection and makes it available to the page.  When theconnection tag completes, it automatically closes the connection.</p><s2 title="Using the connection tag"><example title="houses.jsp">&lt;%@ page import="java.sql.*" %>&lt;%@ taglib prefix="ct" uri="/WEB-INF/conn.tld" %>&lt;h1>House Scores&lt;/h1>&lt;ct:connection name="jdbc/hogwarts">&lt;%Statement stmt = conn.createStatement();ResultSet rs;rs = stmt.executeQuery("select NAME, POINTS from HOUSES");while (rs.next()) {  %>&lt;%= rs.getString(1) %> &lt;%= rs.getInt(2) %>&lt;br>&lt;%}rs.close();stmt.close();%>&lt;/ct:connection></example><results>&lt;h1>House Scores:&lt;/h1>griffindor 482&lt;br>ravenclaw 426&lt;br>hufflepuff 352&lt;br>slytherin 472&lt;br></results><s3 title="&lt;%@ taglib prefix=&quot;ct&quot; ... %&gt;"><p>The taglib declaration configures <var/ct/> as a tag prefix.  Following tagswith the prefix <var/ct/>, like <var/ct:connection/> map to JSP tagimplementations, in this case to instances of ConnectionTag.</p><p>The taglib uri, <var/WEB-INF/conn.tld/>, specifies the tag librarydescriptor file.  The tld tells Resin maps tag names to tag classes andspecifies tag attributes.</p></s3><s3 title="&lt;ct:connection name=&quot;jdbc/hogwarts&quot;&gt;"><ul><li>Looks up the DataSource in JNDI.<li>Creates a new Connection<li>Creates a variable, <var/conn/>, holding the connection.<li>Automatically closes the connection at tag close.</ul></s3><s3 title="&lt;/ct:connection&gt;"><p>When the ct:connection tag closes, the tag closes the connection.  By usingthe TryCatchFinally interface, the tag can guarantee it will close the connection with an exception.</p></s3></s2><s2 title="Implementation of the Connection Tag"><example title="ConnectionTag.java">package test;import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;import javax.naming.*;import javax.sql.*;public class ConnectionTag extends TagSupport implements TryCatchFinally {  private Connection conn;  // JNDI name of the connection  private String name;  public void setName(String name)  {    this.name = name;  }  public int doStartTag()    throws ServletException  {    try {      Context env = (Context) new InitialContext().lookup("java:comp/env");      DataSource ds = (DataSource) env.lookup(name);      if (ds != null)        conn = ds.getConnection();    } catch (Exception e) {      throw new ServletException(e);    }    if (conn == null)      throw new ServletException("can't open connection " + name);    pageContext.setAttribute("conn", conn);        return EVAL_BODY_INCLUDE;  }    public void doCatch(Throwable t)    throws Throwable  {    throw t;  }  public void doFinally()  {    try {      Connection conn = this.conn;      this.conn = null;      pageContext.removeAttribute("conn");      conn.close();    } catch (Exception e) {    }  }}</example><s3 title="implements TryCatchFinally"><p>The new TryCatchFinally interface of JSP 1.2 lets tags handle exceptionsgracefully.  The ConnectionTag uses the doFinally() method of TryCatchFinallyclose the connection even when an exception occurs.</p></s3><s3 title="setName(name)"><p>Attributes in JSP tags use Bean methods to set values.  When Resin evaluatesthe ct:connection tag, it will call setName with the <var/name/> value.  Inthis example, it will call <var/setName("jdbc/hogwarts")/>.</p><p>The database name, jdbc/hogwarts, matches its configuration in theresin.conf or web.xml as described in the <a href='db-config.xtp'>databaseconfig</a>page.</p></s3><s3 title="doStartTag()"><p>Resin calls ConnectionTag's doStartTag method after setting the attributes.Typically a passthrough tag like ConnectionTag will return <var/EVAL_BODY_INCLUDE/> so JSP will interpret the contents asnormal JSP.</p></s3><s3 title="new InitialContext()"><p>The database is stored using JNDI, the Java Naming and Directory Interface.The lookup() method used in this example is sufficient for 90% of projects.</p><p>JNDI provides a global singleton, InitialContext, and namespace, lettingapplications grab configuration information from any class.  JNDI is nicesince you don't need to pass around a configuration variable.  You can justuse InitialContext where you need it.</p><p>In the example, the database source is stored injava:comp/env/jdbc/hogwarts.  The <a href='db_form.xtp'>database form</a>example uses the same JNDI pattern to grab its database.</p></s3><s3 title="ds.getConnection()"><p>With Java's database interface, JDBC, applications grab connections froma data source.  With Resin, the data source automatically pools databaseconnections.</p></s3><s3 title="pageContext.setAttribute"><p><var/ct:connection/> creates a new Java variable, <var/conn/>.  ConnectionTagpasses the connection to the JSP page by setting the conn attribute in thepageContext.  pageContext is a protected variable inherited from theTagSupport class and set by the JSP page before calling any other methods.</p></s3><s3 title="doFinally()"><p>Applications must always close connection objects.  Failing to close theconnection will give the connection pool fits.  By using theTryCatchFinally interface and implementing doFinally(), ConnectionTag canmake sure the connection is always closed even when exceptions happen.</p></s3></s2><s2 title="Declaring Variables"><p>Because the ct:connection tag creates new variables in the JSP page, thetag library needs to create a tag info class to declare the variables.</p><p>The tag info class returns an array of all the variables.  This examplehas a single variable, conn, which has the type java.sql.Connection.  Thevariable is only valid inside the tag, so its scope is VariableInfo.NESTED.</p><example title="Tag Info">package test;import javax.servlet.jsp.tagext.*;public class ConnectionTagInfo extends TagExtraInfo  {  public VariableInfo []getVariableInfo(TagData data)  {    VariableInfo []info = new VariableInfo[1];    info[0] = new VariableInfo("conn", "java.sql.Connection",                               true, VariableInfo.NESTED);    return info;  }}</example></s2><s2 title="Taglib Configuration"><p>The tag library descriptor (tld) associates the tag name, connection, withthe tag class test.ConnectionTag and the tag info classtest.ConnectionTagInfo.</p><p>The tag has a single attribute, name, which is required.</p><example title="WEB-INF/conn.tld">&lt;taglib>  &lt;tag>    &lt;name>connection&lt;/name>    &lt;tagclass>test.ConnectionTag&lt;/tagclass>    &lt;teiclass>test.ConnectionTagInfo&lt;/teiclass>    &lt;attribute>      &lt;name>name&lt;/name>      &lt;required>true&lt;/required>    &lt;/attribute>  &lt;/tag>&lt;/taglib></example></s2><s2 title="Database Configuration"><p>The <a href="db-config.xtp">database configuration</a> example morefully describes the database configuration.</p><example title='resin.conf'>&lt;caucho.com&gt;&lt;resource-ref>  &lt;res-ref-name>jdbc/hogwarts&lt;/res-ref-name>  &lt;res-type>javax.sql.DataSource&lt;/res-type>  &lt;init-param driver-name="org.gjt.mm.mysql.Driver"/>  &lt;init-param url="jdbc:mysql://localhost:3306/test_hogwarts"/>  &lt;init-param user="ferg"/>  &lt;init-param password="changeit"/>&lt;/resource-ref>&lt;http-server>  ...&lt;/http-server>&lt;/caucho.com&gt;</example><s3 title='resource-ref'><p>A resource-ref describes a factory resource.  When Resin initializes, it willcreate the factory and store it in the JNDI context.</p></s3><s3 title='res-ref-name'><p>res-ref-name gives the JNDI name.  The value of res-ref-name is appended tojava:comp/env.  So this example will produce the full JNDI name ofjava:comp/env/jdbc/hogwarts.</p></s3><s3 title='res-type'><p>res-type describes the type of the resource.  This example is a JDBC datasource, so it uses the name javax.sql.DataSource.  An applications couldreplace res-type with an arbitrary bean names; Resin would instantiate,initialize and bind the bean to the JNDI context.</p></s3><s3 title='init-param'><p>init-param uses Bean introspection to initialize the new resource.  Theparameter name is converted to a method name.  For example, driver-name mapsto setDriverName and url maps to setURL.  After creating the new resource,Resin will call all the initializers to configure it.</p></s3></s2></s1>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -