Java Web 实验九 JDBC数据库访问二

必做题

  • 完成全部查询和条件查询
  • 用MVC模式完成查询全部记录及按关键字商品号查询(精确查询)。

需求分析

domain
->Book.java

DAO
->BookDao.java 数据库接口
->DaoFactory.java 工厂类,用于生产数据对象
->JDBCUtil01.java 数据库连接工具类
->JDBCBookDaoImpl.java 针对数据库接口的实现

service
->BookService.java 从工厂中取到对象

servlet
->BaseServlet.java 继承HttpServlet,重写Servlet方法,用于实现Servlet方法的调用,不局限于doPost,doGet方法
->BookService.java 实现查询功能
->InitServlet.java 初始化数据

jsp
->list.jsp 用于显示书本清单,可选择查询

properties
->dao.properies 配置工厂类的实例对象属性
->JDBC.properies 配置数据库的连接属性

代码

Book.java

package domain;

public class Book {
	private String name;
	private String id;
	private double price;
	private String publish;
	private String author;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getPublish() {
		return publish;
	}
	public void setPublish(String publish) {
		this.publish = publish;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public Book(String name, String id, double price, String publish, String author) {
		super();
		this.name = name;
		this.id = id;
		this.price = price;
		this.publish = publish;
		this.author = author;
	}
	public Book() {
		super();
	}
	
	
}

BookDao.java

package DAO;

import java.util.List;

import domain.Book;

public interface BookDao {
	// 全部查询
	public List<Book> selectAll() ;
	
	// 书名查询
	public List<Book> selectByName(String name);
	
	// 编号查询
	public List<Book> selectById(String id);

}

DaoFactory.java

package DAO;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class DaoFactory {
	/*
	 * 工厂类
	 * 返回一个具体的Book实现对象
	 * 通过类名称,完成创建对象(反射完成)
	 */
	
	// 加载配置文件
	private static Properties props = null;
	static {
		try {
			InputStream in = JDBCUtil01.class.getClassLoader()
					.getResourceAsStream("dao.properties");
			props = new Properties();
			props.load(in);
		}catch(IOException e) {
			throw new RuntimeException(e);
		}
	}
	public static BookDao getBookDao(){
		// 得到类名
		String daoClassName = props.getProperty("DAO.BookDao");
		//通过反射来创建实现类
		try {
			Class clazz = Class.forName(daoClassName);
			return (BookDao) clazz.newInstance();
		}catch(Exception e) {
			throw new RuntimeException(e);
		}
		
	}
}

JDBCUtil01.java

package DAO;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class JDBCUtil01 {
	private static Properties props = null;
	
	static {
		try {
			InputStream in = JDBCUtil01.class.getClassLoader()
					.getResourceAsStream("dbconfig.properties");
			props = new Properties();
			props.load(in);
		}catch(IOException e) {
			throw new RuntimeException(e);
		}
		
		try {
			Class.forName(props.getProperty("driverClassName"));
		}catch(ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static Connection getConnection() throws SQLException {
		
		return DriverManager.getConnection(
				props.getProperty("url"),
				props.getProperty("username"),
				props.getProperty("password"));
	}
}

JDBCBookDaoImpl.java

package DAO;

import java.sql.*;
import java.util.ArrayList;
import domain.Book;
/*
 * 针对数据库的实现类
 * 
 * 第一步:连接
 * 第二部:准备sql模板,得到pstmt对象
 * 第三步:执行
 * 
 */
public class JDBCBookDaoImpl implements BookDao {

	@Override
	public ArrayList<Book> selectAll() {
		ArrayList<Book> booklist = null;
		booklist = new ArrayList<Book>();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			// 连接
			con = JDBCUtil01.getConnection();
			// 准备sql模板
			String sql = "select * from book";
			// 得到pstmt
			pstmt = con.prepareStatement(sql);
			// 执行
			rs = pstmt.executeQuery();
			
			// 将查询结果rs转换成Book类型,返回!
			while(rs.next()) {
				// orm(关系对象映射)返回Book对象
				Book book = new Book(rs.getString("Name"),
									 rs.getString("id"),
									 rs.getDouble("price"),
									 rs.getString("publish"),
									 rs.getString("author"));
				booklist.add(book);
			}
		}catch(Exception e) {
			throw new RuntimeException(e);
		}finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(con != null) con.close();
			}catch(SQLException e) {
				throw new RuntimeException(e);
			}
			
		}
		return booklist;
	}

	// 按名称查询
	public ArrayList<Book> selectByName(String name) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ArrayList<Book> booklist = null;
		booklist = new ArrayList<Book>();
		try {
			// 连接
			con = JDBCUtil01.getConnection();
			// 准备sql模板
			String sql = "select * from book where Name=?";
			// 得到pstmt
			pstmt = con.prepareStatement(sql);
			// 为pstmt中的问号赋值
			pstmt.setString(1,name);
			// 执行
			rs = pstmt.executeQuery();

			// 将查询结果rs转换成Book类型,返回!
			if(rs.next()) {
				
				// orm(关系对象映射)返回Book对象
				Book book = new Book(rs.getString("Name"),
									 rs.getString("id"),
									 rs.getDouble("price"),
									 rs.getString("publish"),
									 rs.getString("author"));
				booklist.add(book);
			}
		}catch(Exception e) {
			throw new RuntimeException(e);
		}finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(con != null) con.close();
			}catch(SQLException e) {
				throw new RuntimeException(e);
			}
			
		}
		return booklist;
	}

	// 按ID号查询
	public ArrayList<Book> selectById(String id) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ArrayList<Book> booklist = null;
		booklist = new ArrayList<Book>();
		try {
			// 连接
			con = JDBCUtil01.getConnection();
			// 准备sql模板 
			String sql = "select * from book where id=?";
			// 得到pstmt
			pstmt = con.prepareStatement(sql);
			// 为pstmt中的问号赋值
			pstmt.setString(1,id);
			// 执行
			rs = pstmt.executeQuery();
			
			// 将查询结果rs转换成Book类型,返回!
			if(rs.next()) {
				// orm(关系对象映射)返回Book对象
				Book book = new Book(rs.getString("Name"),
									 rs.getString("id"),
									 rs.getDouble("price"),
									 rs.getString("publish"),
									 rs.getString("author"));
				booklist.add(book);
			}
		}catch(Exception e) {
			throw new RuntimeException(e);
		}finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(con != null) con.close();
			}catch(SQLException e) {
				throw new RuntimeException(e);
			}
		}
		return booklist;
	}

}

BookService.java

package Service;

import java.util.List;

import DAO.BookDao;
import DAO.DaoFactory;
import domain.Book;

public class BookService {
	/*
	 * 业务逻辑类
	 */
	private BookDao bookDao = DaoFactory.getBookDao();
	
	// 展示所有书
	public List<Book> showAll() {
		return bookDao.selectAll();
	}
	
	// 按书名进行搜索
	public List<Book> selectByName(String name) {
		return bookDao.selectByName(name);
	}
	
	// 按编号搜索
	public List<Book> selectById(String id) {
		return bookDao.selectById(id);
	}
}


BaseServlet.java


package Servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public abstract class BaseServlet extends HttpServlet {
	public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取参数
		String methodName = request.getParameter("method");
		if(methodName == null || methodName.trim().isEmpty()) {
			throw new RuntimeException("您没有传递method参数!无法确定您要调用的方法!");
		}
		
		// 得到方法名后,通过反射来确定所调用的方法
		Class c = this.getClass();
		Method method = null;
		try {
			method = c.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
		}catch(Exception e) {
			throw new RuntimeException("不存在"+methodName+"方法");
		}
		try {
			String result = (String) method.invoke(this, request,response);
			// 如果什么都没有,那就什么都不做
			if(result == null || result.trim().isEmpty()) {
				return;
			}
			if(result.contains(":")) {
				// 使用冒号分隔字符串
				int index = result.indexOf(":"); 
				String s = result.substring(0,index);
				String path = result.substring(index+1);
				if(s.equalsIgnoreCase("r")) {
					response.sendRedirect(request.getContextPath()+path);
				}else if(s.equalsIgnoreCase("f")){
					request.getRequestDispatcher(path).forward(request, response);
				}else {
					throw new RuntimeException("您输入的命令当前版本无法支持!");
				}
			}
			// 不存在,默认为请求转发
			else {
				request.getRequestDispatcher(result).forward(request,response);
			}
			
		}catch(Exception e) {
			throw new RuntimeException("您所调用的方法内部出现异常!");
		}
		
	}

}

BookServlet.java

package Servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import Service.BookService;

/**
 * Servlet implementation class BookServlet
 */
@WebServlet("/BookServlet")
public class BookServlet extends BaseServlet {
	private BookService bookService = new BookService();
	
	public String showAll(HttpServletRequest request, 
			HttpServletResponse response) 
					throws ServletException, IOException {
		request.setAttribute("booklist",bookService.showAll());
		return "f:/list.jsp";
	}
	
	public String selectByName(HttpServletRequest request, 
			HttpServletResponse response) 
					throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String name = request.getParameter("selectByName");
		// 解决乱码
		name = new String(name.getBytes("iso-8859-1"),"utf-8");
		request.setAttribute("booklist",bookService.selectByName(name));
		return "f:/list.jsp";
	}
	
	public String selectById(HttpServletRequest request, 
			HttpServletResponse response) 
					throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String id = request.getParameter("selectById");
		// 解决乱码
		id = new String(id.getBytes("iso-8859-1"),"utf-8");
		response.getWriter().print(id);
		request.setAttribute("booklist",bookService.selectById(id));
		return "f:/list.jsp";
	}
	
}

InitServlet.java

package Servlet;
/*
 * 测试类
 */
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Service.BookService;

@WebServlet("/InitServlet")
public class InitServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BookService bookService = new BookService();
		request.setAttribute("booklist",bookService.showAll());
		request.getRequestDispatcher("list.jsp").forward(request, response);
	}
}

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>welcome</title>
</head>
<body>
<h1 align="center">欢迎购书</h1>
<c:choose>
<c:when test="${empty booklist}">
<a href="<c:url value='/BookServlet?method=showAll'/>">返回首页</a>
<h2 align="center"/>没有查询数据!</h2>
</c:when>
<c:otherwise>
<table align="center">
<tr>
<td>
<form action="<c:url value='/BookServlet'/>" method="post"> 
<input type="hidden" name="method" value="selectByName"/>
按书名查询:<input type="text" name="selectByName" /> &nbsp;
<input type="submit" value="查询"/>
 </form>
 </td>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<td>
<!-- 中间的jstl标签用于获取项目名称 -->
<form action="<c:url value='/BookServlet'/>" method="post">
<input type="hidden" name="method" value="selectById"/>
按编号查询:<input type="text" name="selectById" /> &nbsp;
<input type="submit" value="查询"/>
</form>
</td>
</tr>
</table>

<p>
<table border='1' cellspacing='0' align="center" style='width:60%'>
<tr>
<td>排序</td><td>书名</td><td>编号</td><td>单价</td><td>出版社</td><td>作者</td>
</tr>
<c:forEach items="${booklist }" var="book" varStatus="status">
<tr>
<td>${status.count}</td>
<td>${book.name }</td>
<td>${book.id }</td>
<td>${book.price }</td>
<td>${book.publish }</td>
<td>${book.author }</td>
</tr>
</c:forEach>
</table>
</c:otherwise>
</c:choose>
</body>
</html>

dao.properies

DAO.BookDao=DAO.JDBCBookDaoImpl

JDBC.properies

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/store
username=root
password=

运行截图

  1. 初始页面,把书库中的书都展示出来
    在这里插入图片描述

  2. 按书名查询
    在这里插入图片描述

  3. 按Id号查询
    在这里插入图片描述

  4. 若搜索不到,显示该页面
    在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值