本文主要介紹如何快速利用 jsp+taglib+javaBean 構(gòu)建動(dòng)態(tài)數(shù)據(jù)庫(kù)查詢模板的全過程,已經(jīng)如和使用,擴(kuò)展該模板的方法.
在使用該框架之前,我們知道通常如果我們需要利用web查詢數(shù)據(jù)庫(kù)通常是用我們所說的
Model 1 ,和 Model 2 即MVC.而本文介紹的大致如下圖:

本模板所要實(shí)現(xiàn)的功能是: 通過非常簡(jiǎn)單地繼承一個(gè)模板中的方法產(chǎn)生類,和添加一個(gè)含有Tag的簡(jiǎn)單JSP來實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)庫(kù)查詢. 廢話不說了, 現(xiàn)在開始.
1 配置 Tomcat5.0 (或以上版本,我使用了JSP2.0版本的一些功能) 連接池 ,
打開tomcat_hoem/conf/server.xml文件,找到</Host>,在它之前添加如下語(yǔ)句
<Context path="/WebModule1" docBase="WebModule1"
debug="5" reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_DBTest_log." suffix=".txt"
timestamp="true"/>
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/TestDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>org.gjt.mm.mysql.Driver</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/student?autoReconnect=true</value>
</parameter>
</ResourceParams>
</Context>
說明一下, WebModule1 表示你在tomcat_home/webapp 下所建立的文件夾名稱,由于我使用的是MySql數(shù)據(jù)庫(kù),所以driverClassName當(dāng)然是org.gjt.mm.mysql.Driver了, ( 不要告訴我你不知道要將mm.mysql-2.0.4-bin.jar放入Tomcat 5.0\common\lib下哦)至于url,我的是jdbc:mysql://localhost:3306/student?autoReconnect=true 其中,我所選的庫(kù)名稱是student.
2 建立數(shù)據(jù)庫(kù)和表, 當(dāng)然既然我們說的是模板,那么數(shù)據(jù)庫(kù)選擇,和測(cè)試表就由讀者任意了
我選的是student 庫(kù)下的room表作為測(cè)試的.內(nèi)容如下

3 編寫標(biāo)志處理器,并保存到你的Web-inf/
package mytag;
import java.io.*;
import java.util.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class TableShow extends SimpleTagSupport {
private HashMap hp = null;
private String width = null;
public void setHp(HashMap hp) {
this.hp = hp;
}
public void setWidth(String wd) {
this.width = wd;
}
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
String columu_name[] = (String[]) hp.get("column_name");
int sizeOfColumn = ((Integer) hp.get("sizeOfColumn")).intValue();
ArrayList data = (ArrayList) hp.get("data");
Iterator it = data.iterator();
if (width != null) {
out.println("<table width=\"" + width +
"\" border=\"1\" cellspacing=\"0\" align=\"center\">");
} else {
out.println(
"<table border=\"1\" cellspacing=\"0\" align=\"center\">");
}
out.println(" <tr bgcolor=\"#00FF99\"> ");
for (int i = 0; i < sizeOfColumn; i++) {
out.println("<td>");
out.println(columu_name[i]);
out.println(" </td>");
}
out.println(" </tr> ");
while (it.hasNext()) {
String[] value = (String[]) it.next();
out.println("<tr>");
for (int j = 0; j < sizeOfColumn; j++) {
out.println(" <td> ");
out.println(value[j]);
out.println(" </td> ");
}
}
out.println("</table>");
}
}
我想有必要先將大概思想說一下, 標(biāo)志處理器首先通過傳遞來的屬性hp,類型為HashMap,(為什么要用HashMap,看不明白的先不管,我等會(huì)在說.)分析出要生成表格的大小,列數(shù),名稱等等.然后在利用標(biāo)簽的最大優(yōu)勢(shì),標(biāo)志對(duì)運(yùn)行環(huán)境的了解,容易復(fù)用,而且更容易使用. 它實(shí)現(xiàn)了javax.servlet.jsp.tagext. SimpleTagSupport (Jsp2.0中新添加的)接口,而JavaBean雖然也可以實(shí)現(xiàn)這個(gè)接口,但是只有在Web容器中這才有意義..
.4編寫標(biāo)志庫(kù)描述項(xiàng) ,保存為WebModule1\WEB-INF\tlds\ MyTag.tld
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by Taglib Descriptor Wizard -->
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<short-name>MyTag</short-name>
<tag>
<name>table</name>
<tag-class>mytag.TableShow</tag-class>
<body-content>empty</body-content>
<attribute>
<name>hp</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>width</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
這里我聲明了兩個(gè)屬性一個(gè)是hp,是必須要選擇的,另外一個(gè)是將要?jiǎng)討B(tài)生成表格的寬度值
5編寫數(shù)據(jù)庫(kù)連接工廠類
package myFram.util;
import javax.sql.DataSource;
import javax.naming.*;
import java.sql.*;
public class SQLFactory {
private static DataSource ds=null;
private static Object Lock=new Object();
//生成DataSource**
public static DataSource gainDataSource(){
try{
if(ds==null){
synchronized(Lock){
if(ds==null){
Context ctx=new InitialContext();
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
}
}
}
}
catch(NamingException e){e.printStackTrace();}
return ds;
}
//生成SQL連接**
public static synchronized Connection gainConnection(){
Connection con=null;
try{
if(ds==null){
gainDataSource();
}
con=ds.getConnection();
}
catch(SQLException e){e.printStackTrace();}
return con;
}
//釋放SQL連接**
public static void releaseConnection(ResultSet rs,PreparedStatement ps,Statement sql,Connection con){
try{
if(rs!=null)
rs.close();
}
catch(SQLException e){e.printStackTrace();}
try{
if(ps!=null)
ps.close();
}
catch(SQLException e){e.printStackTrace();}
try{
if(sql!=null)
sql.close();
}
catch(SQLException e){e.printStackTrace();}
try{
if(con!=null&&!con.isClosed())
con.close();
}
catch(SQLException e){e.printStackTrace();}
}
}
這里沒有什么好說明的,一看就知道了.
6 編寫方法生成類
package myFram.util;
import java.util.*;
import java.sql.*;
public class MethodGenerator {
private String[] columu_name = null;
private ArrayList data = null;
private HashMap hp = new HashMap();
private Connection con = null;
// private Statement sql = null;
private ResultSet rs = null;
private ResultSetMetaData rm = null;
private int columnCount;
public HashMap getStatementResult(String strsql) {
Statement sql = null;
try {
con = SQLFactory.gainConnection();
sql = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = sql.executeQuery(strsql);
rm = rs.getMetaData();
columnCount = rm.getColumnCount();
columu_name = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
int j = i + 1;
columu_name[i] = rm.getColumnName(j);
}
data = new ArrayList();
while (rs.next()) {
String[] dataInRs = new String[columnCount];
for (int q = 0; q < columnCount; q++) {
int t = q + 1;
dataInRs[q] = rs.getString(t);
if (dataInRs[q] == null || dataInRs[q].equals("")) {
dataInRs[q] = " ";
}
}
data.add(dataInRs);
}
hp.put("sizeOfColumn", new Integer(columnCount));
hp.put("column_name", columu_name);
hp.put("data", data);
} catch (SQLException e) {
e.printStackTrace();
} finally {
SQLFactory.releaseConnection(rs, null, sql, con);
}
return hp;
}
public HashMap getPreparedStatement(String strsql, String[] parameters) {
PreparedStatement sql = null;
try {
con = SQLFactory.gainConnection();
sql = con.prepareStatement(strsql);
for (int i = 0; i < parameters.length; i++) {
int p = i + 1;
if (parameters[i] != null || parameters[i].equals("")) {
sql.setString(p, parameters[i]);
}
}
rs = sql.executeQuery();
rm = rs.getMetaData();
columnCount = rm.getColumnCount();
columu_name = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
int j = i + 1;
columu_name[i] = rm.getColumnName(j);
}
data = new ArrayList();
while (rs.next()) {
String[] dataInRs = new String[columnCount];
for (int q = 0; q < columnCount; q++) {
int t = q + 1;
dataInRs[q] = rs.getString(t);
if (dataInRs[q] == null || dataInRs[q].equals("")) {
dataInRs[q] = " ";
}
}
data.add(dataInRs);
}
hp.put("sizeOfColumn", new Integer(columnCount));
hp.put("column_name", columu_name);
hp.put("data", data);
} catch (SQLException e) {
e.printStackTrace();
} finally {
SQLFactory.releaseConnection(rs, sql, null, con);
}
return hp;
}
}
這就是我們要繼承類了,有兩個(gè)方法分別是HashMap getStatementResult(String strsql),和public HashMap getPreparedStatement(String strsql, String[] parameters),可以看到都返回的是一個(gè)HashMap,思想是通過strsql,參數(shù)調(diào)用已經(jīng)包裝好的方法,再分析查詢結(jié)果的屬性,包括String[] columu_name, int sizeOfColumn, ArrayList data這些都不需要讀者處理,與第一個(gè)函數(shù)不同的是HashMap getPreparedStatement(String strsql, String[] parameters),它處理了含有參數(shù)的查詢,這里要我們提供的 除了strsql之外的parameters值,要求按照順序以此寫入.這里思路很明確,之所以要大動(dòng)干戈的將這么多參數(shù)放入HashMap中為的是我們以后動(dòng)態(tài)表格生成時(shí)使用.
看到這里也許有人要說每次要生成的這么復(fù)雜的HashMap系統(tǒng)開銷一定不少,是的,任何事情都不是完美的. 但是當(dāng)然閱讀完了此文后也許會(huì)感到卻是這樣做是無(wú)有所值的.
好了,到這里就介紹完了,讓我們一起看看是不是簡(jiǎn)化了我們以前的方式.
1 繼承MethodGenerator類
package myFram;
import myFram.util.MethodGenerator;
import java.util.*;
public class UserQuery2 extends MethodGenerator {
HashMap hp = null;
public HashMap getStatementResult() {
String strsql = "select * from room";
hp = getStatementResult(strsql);
return hp;
}
// public HashMap getPreparedStatement(???,???)
public HashMap getPreparedStatement() {
String sql = "select * from room where Name=? and roomid=?";
String[] parameters = new String[2];
parameters[0] = "room1";
parameters[1] = "12";
hp = getPreparedStatement(sql, parameters);
return hp;
}
}
這里可以根據(jù)具體的需要和實(shí)際情況編寫.我這里針對(duì)的是剛才介紹的room表.第一個(gè)方法全表顯示,第二個(gè)帶有參數(shù).至于參數(shù)的來源,即可以通過 jsp,也可以是提前寫好的
2 編寫JSP jsp4.jsp
<%@page contentType="text/html; charset=GB18030" import="java.util.*"%>
<%@taglib uri="/WEB-INF/tlds/MyTag.tld" prefix="mytag"%>
<html>
<head>
<jsp:useBean id="test" scope="page" class="myFram.UserQuery2"/>
<title>jsp4</title>
</head>
<body bgcolor="#ffffff">
<%HashMap hp = test.getPreparedStatement();%>
<mytag:table hp="<%=hp%>" width="500"/>
</body>
</html>
3 ok !! 試驗(yàn)!

還可以稍微改動(dòng)一下jsp4.jsp將<%HashMap hp = test.getPreparedStatement();%>
改為 <%HashMap hp = test.getStatementResult();%> 結(jié)果是

僅僅兩個(gè)簡(jiǎn)單的步驟,省去了我們多少工作,大家一定有體會(huì)的吧~
這里控制器由于這個(gè)例子太簡(jiǎn)單了,Servlet 并沒有用到,讀者可以根據(jù)自己的實(shí)際情況以及復(fù)雜程度自由選擇.
本人正在努力將分頁(yè)以標(biāo)志的形式做到該模板中,屆時(shí)和大家分享.
由于本人水平有限,難免有出錯(cuò)的地方,歡迎提出您的寶貴意見,和改進(jìn)的方法.
QQ: 39315890
Mail:mill_lmq@tom.com
代碼下載:http://www.tkk7.com/Files/limq/code.rar