Processing Tag Bodies

So far, you have seen tags that treat the text in the body of the tag as simple JSP (or HTML) data. But tags can also manipulate the tag body in any way they choose. A simple example would be a tag that interprets its body as an SQL statement and uses this to query the database. Listing 14.18 shows a simple use of such a tag.

Listing 14.18. Full Text of select.jsp
 1: <%@ taglib uri="/demo" prefix="demo" %>
 2: <HTML>
 3: <HEAD>
 4: <TITLE> Tag Library SQL Query Demo</TITLE>
 5: <BODY>
 6:   <demo:select>
 7:     SELECT * FROM Customer
 8:   </demo:select>
 9: </BODY>
10: </HTML>
					

The implementation of this select tag must state in the TLD that the body text is tag dependent, as shown in the following:

<tag>
    <name>select</name>
    <tag-class>demo.SelectTag</tag-class>
    <body-content>tagdependent</body-content>
</tag>

The implementation of the select tag must extend the BodyTagSupport class as shown in Listing 14.19. This tag tags an SQL select statement as the tag body and runs this statement against a database (in this case, the Agency Case study database).

Listing 14.19. Full Text of SelectTag.java
 1: package demo;
 2:
 3: import java.io.*;
 4: import java.sql.*;
 5: import javax.sql.*;
 6: import javax.naming.*;
 7: import javax.servlet.jsp.*;
 8: import javax.servlet.jsp.tagext.*;
 9:
10: public class SelectTag extends BodyTagSupport {
11:    public int doEndTag() throws JspException {
12:       try {
13:          String ans = doSelect(bodyContent.getString());
14:          pageContext.getOut().print(ans);
15:          bodyContent.clearBody();
16:       }
17:       catch (Exception ex) {
18:          throw new JspTagException("SqlTag: "+ex);
19:       }
20:       return EVAL_PAGE;
21:    }
22:
23:    private String doSelect (String cmd) throws NamingException, SQLException {
24:       StringBuffer ans = new StringBuffer("<H2>"+cmd+"</H2>");
25:       InitialContext ic = new InitialContext();
26:       DataSource dataSource = (DataSource)ic.lookup("java:comp/env/jdbc/Agency");
27:       Connection con = null;
28:       PreparedStatement stmt = null;
29:       ResultSet rs = null;
30:       try {
31:           con = dataSource.getConnection();
32:           stmt = con.prepareStatement(cmd);
33:           rs = stmt.executeQuery();
34:           ans.append("<TABLE border=1>");
35:           ResultSetMetaData rsmd = rs.getMetaData();
36:           int numCols = rsmd.getColumnCount();
37:           // get column header info
38:           ans.append("<TR>");
39:           for (int i=1; i <= numCols; i++) {
40:               ans.append("<TH>");
41:               ans.append(rsmd.getColumnLabel(i));
42:               ans.append("</TH>");
43:           }
44:           ans.append("</TR>");
45:           // get cmma separated data
46:           while (rs.next()) {
47:               ans.append("</TR>");
48:               for (int i=1; i <= numCols; i++) {
49:                   ans.append("<TD>");
50:                       ans.append(rs.getString(i));
51:                   ans.append("</TD>");
52:               }
53:               ans.append("</TR>");
54:           }
55:           ans.append("</TABLE>");
56:       }
57:       finally {
58:           if (rs != null) {
59:               try {rs.close();} catch (SQLException ex) {}
60:           }
61:           if (stmt != null) {
62:               try {stmt.close();} catch (SQLException ex) {}
63:           }
64:           if (con != null) {
65:               try {con.close();} catch (SQLException ex) {}
66:           }
67:       }
68:       return ans.toString();
69:    }
70: }
					

The BodyTagSupport processing buffers up the body text in the bodyContent variable and the doEndTag() method retrieves the tag body and hands it on to the private helper method doSelect() for execution as an SQL SELECT statement.

The doSelect() method queries the database (using a registered JNDI data source) and formats the results as an HTML table. The doAfterBody() method prints out the results of the SQL query and clears down the body content buffer.

Listing 14.19 shows a very simple example of what can be achieved by using custom tags. A simple variation of this Web page is to provide a form that lets the user select the customer name and change the query to show the details for a single customer passed in as a request parameter called "customer". The new JSP would be like the following:

<%@ taglib uri="/demo" prefix="demo" %>
<HTML>
<HEAD>
<TITLE> Tag Library SQL Query Demo</TITLE>
<BODY>
  <demo:select>
    SELECT * FROM Customer WHERE login = <%=request.getParamter("customer")%>
  </demo:select>
</BODY>
</HTML>

The possibilities of this approach are endless. The fact that any custom tag can retrieve the body content and manipulate the text provides complete flexibility in how a JSP can be written.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.160.181