JSTL標籤及顯示資料庫資訊
1. 建立資料庫
mysql> create database myWeb;
Query OK, 1 row affected (0.00 sec)
mysql> use myWeb;
Database changed
mysql> create table customers(
-> customerId varchar(20) primary key,
-> name varchar(20),
-> phone varchar(20)
-> );
Query OK, 0 rows affected (0.06 sec)
mysql> insert into customers(customerId,name,phone) value('001','gao','12345');
Query OK, 1 row affected (0.03 sec)
mysql> insert into customers(customerId,name,phone) value('002','li','1257');
Query OK, 1 row affected (0.03 sec)
2. 編寫一個對映資料庫中的表的類
package beans;
publicclass Customer {
private String cusid,cusname,cusphone;
public Customer()
{
}
public String getCusid() {
return
}
publicvoid setCusid(String cusid) {
this.cusid = cusid;
}
public String getCusname() {
returncusname;
}
publicvoid setCusname(String cusname) {
this.cusname = cusname;
}
public String getCusphone() {
returncusphone;
}
publicvoid setCusphone(String cusphone) {
this.cusphone = cusphone;
}
}
3. 編寫一個操作類,實現資料庫的查詢
package dao;
import java.sql.*;
import java.util.*;
import beans.Customer;
publicclass CustomerDao {
public List<Customer> allCustomers()
{
List<Customer> list=new ArrayList<Customer>();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/myWeb", "root", "sql");
Statement cmd=con.createStatement();
ResultSet rs=cmd.executeQuery("select * from customers");
while(rs.next())
{
Customer c=new Customer();
c.setCusid(rs.getString(1));
c.setCusname(rs.getString(2));
c.setCusphone(rs.getString(3));
list.add(c);
}
}
catch(Exception ex)
{}
return list;
}
}
4. 編寫jsp客戶端,呼叫操作類。並使用JSTL標籤顯示顧客資訊
<%@ page contentType="text/html;charset=gb2312"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="dao.CustomerDao,java.util.*,beans.Customer" %>
<html>
<body>
<%
CustomerDao dao=new CustomerDao();
List<Customer> clist=dao.allCustomers();
pageContext.setAttribute("cuslist",clist);
%>
<table>
<tr>
<td>顧客ID</td>
<td>姓名</td>
<td>聯絡電話</td>
</tr>
<c:forEach var="cus" items="${cuslist}">
<tr>
<td>${cus.cusid }</td>
<td>${cus.cusname }</td>
<td>${cus.cusphone }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
執行結果: