作品要求
1、能使用Jsp、JavaBean、JDBC、servlet和mysql数据库或SqlServer2008技术编写一个图书管理系统,可以实现用户注册、用户登陆、分页查询所有图书信息、编辑图书信息、删除给定图书、使用jsp技术保存客户端信息;
2、能结合JSTL+EL完成所有JSP页面改造;
3、系统整体布局设计精美、代码结构层次清楚;
项目结构
准备工作
1.按照项目结构创建相关包
2.导入相关包放在lib文件夹下,并添加为库
3.创建数据库连接类DBHelper.java放在utils包下
import java.sql.*;
public class DBHelper {
private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String URL = "jdbc:mysql://localhost:3306/librarySystem?characterEncoding=UTF-8"; //此处librarySystem写自己的数据库名称
private final static String USER = "root";//此处写自己的用户名
private final static String PWD = "123456";//写自己的密码
static {
try{
Class.forName(DRIVER);
}catch (Exception e){
throw new RuntimeException(e);
}
}
//建立连接
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(URL,USER,PWD);
}
//释放资源
public static void closeAll(Connection conn, Statement st, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
3.创建数据库
1.创建名为 librarysystem 的数据库,字符集为utf8。
2.创建两张表,books,admin
CREATE TABLE admin (
id INT AUTO_INCREMENT,
name VARCHAR(255),
password VARCHAR(255),
PRIMARY KEY (id)
);
CREATE TABLE books (
id INT AUTO_INCREMENT,
title VARCHAR(255),
author VARCHAR(255),
publisher VARCHAR(255),
price DECIMAL(10, 2),
PRIMARY KEY (id)
);
3.插入相关信息
INSERT INTO `admin` VALUES (1, 'admin', '123456');
INSERT INTO `books` VALUES (1, '《Java程序设计基础》', '陈国君', '清华大学出版社', 66.00);
INSERT INTO `books` VALUES (2, '《沸羊羊舔狗日记》', '美羊羊', '羊村出版社', 666.00);
INSERT INTO `books` VALUES (3, '《伞兵一号》', '卢本伟', '伞兵出版社', 66.60);
INSERT INTO `books` VALUES (4, '《1984》', '乔治·奥威尔', '译林出版社', 58.00);
INSERT INTO `books` VALUES (5, '《小王子》', '安托万·德·圣-埃克苏佩里', '中国友谊出版公司', 25.00);
INSERT INTO `books` VALUES (6, '《骆驼祥子》', '老舍', '人民文学出版社', 22.00);
INSERT INTO `books` VALUES (7, '《麦田里的守望者》', 'J.D.塞林格', '译林出版社', 39.00);
INSERT INTO `books` VALUES (8, '《挪威的森林》', '村上春树', '上海译文出版社', 55.00);
INSERT INTO `books` VALUES (9, '《哈姆雷特》', '莎士比亚', '人民文学出版社', 35.00);
INSERT INTO `books` VALUES (10, '《简爱》', '夏洛蒂·勃朗特', '人民文学出版社', 49.00);
INSERT INTO `books` VALUES (11, '《飘》', '玛格丽特·米切尔', '译林出版社', 68.00);
功能实现
1.登录界面:创建login.jsp(注意放置位置)
注:图片统一放在imges文件夹下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri ="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<style>
body {
background-image: url("images/img.png");
background-repeat: no-repeat;
background-size: cover;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
width: 300px;
margin: 100px auto;
background-color: rgba(255, 255, 255, 0.7);
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
/*align-items: center;
justify-content: center;*/
}
h2 {
text-align: center;
color: #333;
}
form {
display: flex;
flex-direction: column;
}
label {
font-weight: bold;
margin-bottom: 5px;
}
input[type="text"], input[type="password"] {
width: 100%;
padding: 5px;
border: 1px solid #ccc;
border-radius: 3px;
}
a{
text-decoration: none;
color: #333;
}
input[type="submit"] {
background-color: #4CAF50;
color: #fff;
border: none;
padding: 10px;
border-radius: 3px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
<script>
</script>
</head>
<body>
<div class="container">
<h2>用户登录</h2>
<c:if test="${not empty errorMessage}">
<p style="color: red">${errorMessage}</p>
</c:if>
<form action="LoginServlet" method="post">
<label for="name">用户名:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
<br>
<a href="register.jsp">暂无用户?点击注册</a>
<br>
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
界面展示
2.注册界面及实现
1.创建register.jsp(注意放置位置)
实现的功能:
1.检查用户名是否已经存在。
2.两次输入密码是否一致。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri ="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
<style>
body {
background-image: url("images/bg2.jpg");
background-repeat: no-repeat;
background-size: cover;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
a{
text-decoration: none;
color: #333;
}
.container {
width: 300px;
margin: 100px auto;
background-color: rgba(255, 255, 255, 0.7);;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h2 {
text-align: center;
color: #333;
}
form {
display: flex;
flex-direction: column;
}
label {
font-weight: bold;
margin-bottom: 5px;
}
input[type="text"], input[type="password"] {
width: 100%;
padding: 5px;
border: 1px solid #ccc;
border-radius: 3px;
}
input[type="submit"] {
background-color: #4CAF50;
color: #fff;
border: none;
padding: 10px;
border-radius: 3px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>用户注册</h2>
<c:if test="${not empty message}">
<p style="color: red">${message}</p>
</c:if>
<form action="Register" method="post" onsubmit="return validatePassword()">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
<br>
<label for="confirmPassword">确认密码:</label>
<input type="password" id="confirmPassword" name="confirmPassword" required>
<br>
<a href="login.jsp">已有账号,返回登录界面</a>
<br>
<input type="submit" value="注册">
</form>
</div>
</body>
<script>
function validatePassword() {
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmPassword").value;
if (password !== confirmPassword) {
alert("密码和确认密码不一致,请重新输入!");
return false;
}
return true;
}
</script>
</html>
注册界面展示
2. 后端代码
1.创建RegisterController.java并放在controller包中
import com.example.javaBean.Admin;
import com.example.service.RegisterService;
import com.example.service.impl.RegisterServiceImpl;
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 java.io.IOException;
@WebServlet("/Register")
public class RegisterController extends HttpServlet {
RegisterService registerService = new RegisterServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=UTF-8");
String name = req.getParameter("username");
//调用check()方法进行检查
int i = registerService.check(name);
System.out.println(i);
if (i == 1){
String message = "用户名已存在,请重新输入!!";
req.setAttribute("message",message);
req.getRequestDispatcher("register.jsp").forward(req,resp);
}
else {
Admin admin = new Admin();
admin.setName(req.getParameter("username"));
admin.setPassword(req.getParameter("password"));
System.out.println(req.getParameter("username"));
registerService.register(admin);
resp.sendRedirect("login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
2.创建RegisterService接口房价service文件夹下
包含register ( ) 和check ( )方法
import com.example.javaBean.Admin;
public interface RegisterService {
void register(Admin admin);
int check(String name);
}
3.创建RegisterServiceImpl.java实现接口,存放在service下的impl包下
import com.example.dao.AdminDao;
import com.example.javaBean.Admin;
import com.example.service.RegisterService;
public class RegisterServiceImpl implements RegisterService {
@Override
public void register(Admin admin) {
AdminDao adminDao = new AdminDao();
adminDao.register(admin);
}
@Override
public int check(String name) {
AdminDao adminDao = new AdminDao();
int i = adminDao.check(name);
return i;
}
}
4.创建AdminDao.java存放在Dao包下
其中包含register ( ) 和check ( )方法
import com.example.javaBean.Admin;
import com.example.utils.DBHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class AdminDao {
//注册方法
public void register(Admin admin) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBHelper.getConn();
String sql = "INSERT INTO admin (name, password) \n" +
"VALUES (?,?);";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,admin.getName());
preparedStatement.setString(2,admin.getPassword());
System.out.println(preparedStatement.executeUpdate());
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
{
DBHelper.closeAll(connection,preparedStatement,null);
}
}
}
//检查方法
public int check(String name){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBHelper.getConn();
String sql = "select name from admin where name = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,name);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
return 1;
}
return 0;
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
{
DBHelper.closeAll(connection,preparedStatement,null);
}
}
}
}
登录验证
查询输入的用户名和密码是否正确
创建LoginController.java并放在controller包下
import com.example.utils.DBHelper;
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 java.io.IOException;
import java.sql.*;
@WebServlet("/LoginServlet")
public class LoginController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取用户名和密码
String name = req.getParameter("name");
String password = req.getParameter("password");
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
//数据库连接
try {
connection = DBHelper.getConn();
String sql = "select * from admin where name = ? and password = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,name);
preparedStatement.setString(2,password);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
String username = name;
req.getSession().setAttribute("name",username);
resp.sendRedirect("ShowBookController");
}
else {
String errorMessage = "用户名或密码不正确,请重新输入!!";
req.setAttribute("errorMessage", errorMessage);
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBHelper.closeAll(connection,preparedStatement,resultSet);
}
}
}
图书管理界面
包括增,删,改,查,退出功能按钮,以及分页查询所有数据。
1.创建index.jsp(注意存放位置)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri ="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>图书管理</title>
<style>
body { background-image: url("images/img4.jpg");
background-repeat: no-repeat;
background-size: cover;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
h1 {
color: white;
padding: 20px;
margin: 0;
text-align: center;
font-size: 30px;
}
h2 {
color: white;
padding: 20px;
margin: 0;
text-align: center;
font-size: 24px;
}
.container {
max-width: 800px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: rgba(255, 255, 255, 0.8);
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #A55D5D;
color: white;
font-weight: bold;
text-align: center;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
tr:hover {
background-color: #e6e6e6;
}
input[type="text"] {
padding: 8px;
border: 1px solid #ddd;
border-radius: 5px;
width: 200px;
}
.button,select{
background-color: #A55D5D;
border: none;
color: white;
padding: 8px 16px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 14px;
margin: 4px 2px;
cursor: pointer;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #A55D5D;
}
#exit{
background-color: red;
border: none;
color: white;
padding: 8px 16px;
text-align:center;
float: right;
text-decoration: none;
display: inline-block;
font-size: 14px;
margin: 4px 2px;
cursor: pointer;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.search-form label {
font-weight: bold;
margin-right: 10px;
}
.search-form input[type="text"] {
width: 300px;
margin-right: 10px;
}
.pagination {
margin-top: 20px;
text-align: center;
}
.pagination a {
color: #4CAF50;
text-decoration: none;
padding: 8px 16px;
margin: 0 4px;
border-radius: 5px;
transition: background-color 0.3s ease;
}
.pagination a:hover {
background-color: #e6e6e6;
}
.add-form label {
font-weight: bold;
margin-right: 10px;
}
.add-form input[type="text"] {
padding: 8px;
border: 1px solid #ddd;
border-radius: 5px;
width: 200px;
margin-right: 10px;
}
.function {
color: #4CAF50;
font-size: 16px;
background-color: transparent;
border: none;
text-decoration: none;
transition: all 0.3s ease;
}
.function:hover {
color: #0056b3;
background-color: #eaf2f8;
}
</style>
</head>
<body>
<h1>图书管理</h1>
<h2>欢迎您!${name}</h2>
<div class="container">
<form action="selectBook" method="post" onsubmit="return validateForm()">
<select class="select" id="select" name="select">
<option value="title">书名</option>
<option value="author">作者</option>
<option value="publisher">出版社</option>
</select>
<input type="text" id="search" name="search" required>
<input type="submit" value="查询" class="button">
</form>
<div>
<input type="button" value="退出" id="exit" onclick="exit()">
<form action="ShowBookController" method="post">
<input type="submit" value="显示所有书籍" class="button">
<input type="button" value="新增" class="button" onclick="add()">
</form>
</div>
<table>
<tr>
<th>ID</th>
<th>书籍名称</th>
<th>作者</th>
<th>出版社</th>
<th>价格</th>
<th>操作</th>
</tr>
<c:forEach items="${book}" var="item" varStatus="i">
<tr>
<td>${item.id}</td>
<td>${item.title}</td>
<td>${item.author}</td>
<td>${item.publisher}</td>
<td>${item.price}</td>
<td>
<a href="updateBook?id=${item.id}" class="function">编辑</a>
<a href="deleteBook?id=${item.id}" class="function" onclick="return confirm('确定要删除吗?')">删除</a>
</td>
</tr>
</c:forEach>
</table>
<div class="pagination">
<span style="color: #4CAF50">当前页数【${currentPage}】</span>
<a href="ShowBookController?page=1">首页</a>
<c:if test="${currentPage > 1}">
<a href="ShowBookController?page=${currentPage-1}">上一页</a>
</c:if>
<c:set var="totalPages" value="${totalPages}" />
<c:forEach var="pageNum" begin="1" end="${totalPages}">
<c:choose>
<c:when test="${pageNum == currentPage}">
<a class="active" href="?page=${pageNum}">${pageNum}</a>
</c:when>
<c:otherwise>
<a href="?page=${pageNum}">${pageNum}</a>
</c:otherwise>
</c:choose>
</c:forEach>
<c:if test="${currentPage<totalPages}">
<a href="ShowBookController?page=${currentPage+1}">下一页</a>
</c:if>
<a href="ShowBookController?page=${totalPages}">尾页</a>
</div>
</div>
</body>
<script>
function add(){
window.location.href='add.jsp';
}
function exit(){
var confirmResult = confirm("确定要退出吗?");
if (confirmResult) {
window.location.href = "login.jsp";
}
}
function validateForm() {
var searchInput = document.getElementById("search").value;
if (searchInput === "") {
alert("请在文本框中输入内容!");
return false;
}
return true;
}
</script>
</html>
分页查询所有数据
1.创建ShowBookController.java并放在controller包下
import com.example.javaBean.Book;
import com.example.service.ShowBookService;
import com.example.service.impl.ShowBookServiceImpl;
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 java.io.IOException;
import java.util.List;
@WebServlet("/ShowBookController")
public class ShowBookController extends HttpServlet {
ShowBookService showBookService = new ShowBookServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// 每页显示的记录数
int pageSize = 10;
int totalCount =showBookService.getPageNum();
System.out.println(totalCount);
// 计算总页数
int totalPages = (int) Math.ceil((double) totalCount / pageSize);
int currentPage =1;
if(req.getParameter("page") != null){
currentPage = Integer.parseInt(req.getParameter("page"));
System.out.println(currentPage);
}
System.out.println(req.getParameter("page"));
List<Book> list = showBookService.getAllBook(pageSize,currentPage);
String message = (String) req.getSession().getAttribute("name");
System.out.println(totalPages);
req.setAttribute("currentPage",currentPage);
req.setAttribute("totalPages",totalPages);
req.setAttribute("book",list);
req.setAttribute("name",message);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
2.创建ShowBookService接口,并存放在service包下
import com.example.javaBean.Book;
import java.util.List;
public interface ShowBookService {
List<Book> getAllBook(int pageSize, int currentPage);
int getPageNum();
}
3.创建ShowBookServiceImpl.java,实现接口
import com.example.dao.BookDao;
import com.example.javaBean.Book;
import com.example.service.ShowBookService;
import java.util.List;
public class ShowBookServiceImpl implements ShowBookService {
BookDao bookDao = new BookDao();
@Override
public List<Book> getAllBook(int pageSize, int currentPage) {
List<Book> list = bookDao.getAllBook(pageSize,currentPage);
return list;
}
@Override
public int getPageNum() {
int totalCount = bookDao.getPageNum();
return totalCount;
}
}
4.创建BookDao.java放在dao包下,实现getAllBook ( )和getPageNum ( )方法。
public List<Book> getAllBook(int pageSize,int currentPage) {
List<Book> bookList = new ArrayList<>();
// 计算起始记录的索引
int startIndex = (currentPage - 1) * pageSize;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBHelper.getConn();
String sql = "select * from books limit ?,?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, startIndex);
preparedStatement.setInt(2, pageSize);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Book book = new Book();
book.setId(resultSet.getInt(1));
book.setTitle(resultSet.getString(2));
book.setAuthor(resultSet.getString(3));
book.setPublisher(resultSet.getString(4));
book.setPrice(resultSet.getDouble(5));
bookList.add(book);
}
System.out.println(bookList);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBHelper.closeAll(connection, preparedStatement, resultSet);
}
return bookList;
}
public int getPageNum() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
int totalCount = 0;
try {
connection = DBHelper.getConn();
String sql = "select count(*) from books";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
totalCount = resultSet.getInt(1);
}
System.out.println(totalCount);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return totalCount;
}
添加书籍功能
1.点击主页面中的新增按钮跳转到add.jsp页面,创建add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>添加书籍</title>
<style>
body {
background-image: url("images/img2.jpg");
background-repeat: no-repeat;
background-size: cover;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
width: 400px;
margin: 50px auto;
padding: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
background-color: rgba(255, 255, 255, 0.7);
}
h2 {
text-align: center;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
font-weight: bold;
margin-bottom: 5px;
}
input[type="text"], input[type="email"], select {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type="submit"] {
width: 100%;
background-color: #4CAF50;
color: #fff;
border: none;
padding: 10px;
border-radius: 4px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<h2>添加书籍</h2>
<form action="addBook" method="post" onsubmit="return add()">
<div class="form-group">
<label for="bookName">书名:</label>
<input type="text" id="bookName" name="bookName" required>
</div>
<div class="form-group">
<label for="author">作者:</label>
<input type="text" id="author" name="author" required>
</div>
<div class="form-group">
<label for="publisher">出版社:</label>
<input type="text" id="publisher" name="publisher" required>
</div>
<div class="form-group">
<label for="price">价格:</label>
<input type="text" id="price" name="price" required>
</div>
<input type="submit" value="添加书籍">
</form>
</div>
</body>
<script>
function add(){
alert("书籍添加成功!最新添加的书籍在尾页哦!!");
return true;
}
</script>
</html>
界面展示
2.创建AddBookController.java并放在controller包下
import com.example.javaBean.Book;
import com.example.service.AddBookService;
import com.example.service.impl.AddBookServiceImpl;
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 java.io.IOException;
@WebServlet("/addBook")
public class AddBookController extends HttpServlet {
AddBookService addBookService = new AddBookServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=UTF-8");
Book book = new Book();
book.setTitle(req.getParameter("bookName"));
book.setAuthor(req.getParameter("author"));
book.setPublisher(req.getParameter("publisher"));
book.setPrice(Double.valueOf((req.getParameter("price"))));
addBookService.add(book);
resp.sendRedirect("ShowBookController");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
3.创建AddBookService接口,并存放在service包下
import com.example.javaBean.Book;
public interface AddBookService {
void add(Book book);
}
4.创建AddBookServiceImpl.java,实现接口
import com.example.dao.BookDao;
import com.example.javaBean.Book;
import com.example.service.AddBookService;
public class AddBookServiceImpl implements AddBookService {
@Override
public void add(Book book) {
BookDao bookDao = new BookDao();
bookDao.add(book);
}
}
5.在BookDao.java 中实现add ( )方法
public void add(Book book){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = DBHelper.getConn();
String sql = "INSERT INTO books (title, author, publisher, price) \n" +
"VALUES (?,?,?,?);";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,book.getTitle());
preparedStatement.setString(2, book.getAuthor());
preparedStatement.setString(3, book.getPublisher());
preparedStatement.setString(4, String.valueOf(book.getPrice()));
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
{
DBHelper.closeAll(connection,preparedStatement,null);
}
}
}