JSP快速入门教程:测试(3)
查询所有图书
1)创建图书表
create table books(
bookid varchar(10) primary key,
bookname varchar(30),
author varchar(20),
price float,
publisher varchar(20)
)
插入一些模拟数据
insert into books values('00001','Java','zhangsan',20,'电子工业')
insert into books values('00002','JSP','lisi',22,'人民邮电')
insert into books values('00003','Java EE','wang',30,'人民邮电')
2)V部分
V主要与人进行交互,要考虑输入和输出
输入:在导航条中添加“查看所有图书”的超链。
输出:显示所有图书信息的JSP文件。
文件名:books.jsp
文件内容:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="header.jsp"%>
图书编号
图书名称
作者
价格
出版社
${book.bookid}
${book.bookname}
${book.author}
${book.price}
${book.publisher}
3)M部分
完成功能:从数据库中查询所有的图书。
文件名:BookBean.java
文件内容:
package bean;
import java.sql.*;
import java.util.ArrayList;
public class BookBean extends Base{
// 描述图书的属性
private String bookid;
private String bookname;
private String author;
private float price;
private String publisher;
// 编写对乘员进行操作的方法
public void setBookid(String bookid){
this.bookid = bookid;
}
public String getBookid(){
return bookid;
}
public void setBookname(String bookname){
this.bookname = bookname;
}
public String getBookname(){
return bookname;
}
public void setAuthor(String author){
this.author = author;
}
public String getAuthor(){
return author;
}
public void setPrice(float price){
this.price = price;
}
public float getPrice(){
return price;
}
public void setPublisher(String publisher){
this.publisher = publisher;
}
public String getPublisher(){
return publisher;
}
public ArrayList findAllBooks(){
ArrayList books = new ArrayList();
String sql = "select * from books";
try{
createStatement(sql);
rs = executeQuery();
// 使用while循环遍历结果集
while(rs.next())
{
// 使用rs的getString方法,以字符串的形式获取第一列,参数也可以是列的名字
// 可以得到当前记录的每一列
String tempBookid = rs.getString(1);
String tempBookname = rs.getString(2);
String tempAuthor = rs.getString(3);
float tempPrice = rs.getFloat(4);
String tempPublisher = rs.getString(5);
// 创建图书对象
BookBean book = new BookBean();
book.setBookid(tempBookid);
book.setBookname(tempBookname);
book.setAuthor(tempAuthor);
book.setPrice(tempPrice);
book.setPublisher(tempPublisher);
// 把书添加到链表中
books.add(book);
}
}catch(Exception e){
System.out.println(e.toString());
}finally{
close();
}
return books;
}
}