2011年12月1日 星期四

JSP 爪哇豆豆

m4_demo_how_to_use_bean.jsp



<%@ page language="java" contentType="text/html; charset=BIG5" pageEncoding="BIG5"%>
<!--DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=BIG5">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id='tu' class='com.my_javabeans' />
<%    tu.JustAmethod("select * from products ");    %>
<%    if (tu.成功) {    %>
<%=       "成功"    %>
          <hr />
<%        if (tu.幾列 == 0) {    %>
              沒有資料
<%        } else {
               String[] each_row;    %>
               有資料
               <br />
               <table>
<%             for (int 第幾筆 = 0; 第幾筆 < tu.幾列; 第幾筆 += 1) {
                   each_row = tu.rows.elementAt(第幾筆);    %>
                   <tr>
<%                 for (int 第幾欄 = 0; 第幾欄 < tu.幾欄; 第幾欄 += 1) {
                       String column;
                       column = each_row[第幾欄];    %>
                       <td><%=column%></td>
<%                 }    %>
                   </tr>
<%             }    %>
               </table>
<%        }    %>
<%    } else {    %>
<%=       "失敗原因:" + tu.失敗原因    %>
<%    }    %>
</body>
</html>


my_javabeans.java


package com;

import java.sql.*;
import java.util.*;

public class my_javabeans {

	public int 幾欄;
	public int 幾列;
	
	public Vector rows;
	public String 失敗原因;
	public boolean 成功;
	
	public void JustAmethod(String query) {
		java.sql.Connection conn = null;
		Statement cmd = null;
		ResultSet dr = null;
		try {
			失敗原因 = "";
			成功 = false;
			rows = new Vector();
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			conn = java.sql.DriverManager.getConnection(
					"jdbc:sqlserver://127.0.0.1:1433;databasename=northwind",
					"sa", "III");

			cmd = conn.createStatement();
			dr = cmd.executeQuery(query);
			ResultSetMetaData rsmd = dr.getMetaData();
			幾欄 = rsmd.getColumnCount();
			
			String [] each_row ;
			幾列 = 0;
			while ( dr.next() ) {
				幾列 += 1;
				each_row = new String[幾欄];
				for(int cn = 1; cn <= 幾欄  ; cn += 1)
				{
					each_row[cn-1]	=  dr.getString(cn);
				}
				rows.addElement(each_row);
			}
			成功 = true;

		} catch (java.sql.SQLException exp) {
			失敗原因 = "資料庫 problem: " + exp.getMessage();
			
		} catch (ClassNotFoundException exp) {
			失敗原因 = "jdbc driver problem: " + exp.getMessage();
		}
	}
}

沒有留言:

張貼留言