使用JSP+JavaBean对数据库进行增删改查操作

运行展示:

代码:

首先是项目的大包:

正常项目中JavaBean和DAO应该放在两个不同的包中,在这因为代码较少,放在一个包内

Books.java:

package Beans;

public class Books {

	private int bookId;
	private String bookName;
	private double price;
	
	 
	public int getBookId() {
		return bookId;
	}
	public void setBookId(int bookId) {
		this.bookId = bookId;
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
}

DAO.java:

package Beans;

import java.util.List;

public interface DAO {

	//查询书单
	public List<Books> findAllBooks();
	//find book by id
	public Books findBookByName(String name);
	//update book
	public void updateBook(Books book);
	//add a new book
	public void addBook(Books book);
	 
	//delete a book by id
	public void deleteBookByName(String name);
}

 DAOImpl.java:

package Beans;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


public class DAOImpl implements DAO {

	public List<Books> findAllBooks(){
		List<Books> list = new ArrayList();
		Books book = null;
		DBUtil util = new DBUtil();
		Connection conn = util.getConnection();
		String sql = "select * from Book";
		try {
			Statement  stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
		 
			while(rs.next()) {
				book = new Books();
				book.setBookId( rs.getInt("bookId"));
				book.setBookName(rs.getString("bookName"));
				book.setPrice(rs.getDouble("price"));
				list.add(book);
			}
			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			 util.closeConnection(conn);
		}
		 
		return list;
	}

	 
	
	public Books findBookByName(String name) {
		// TODO Auto-generated method stub
		DBUtil util = new DBUtil();
		Connection conn = util.getConnection();
		 
		Books b = null;
		String sql = "select * from Book where bookName=? ";
		try {
			PreparedStatement pstmt=
					conn.prepareStatement(sql);
			pstmt.setString(1, name);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()) {
				 b = new Books();
				 b.setBookId(rs.getInt("bookId"));
				 b.setBookName(rs.getString("bookName"));
				 b.setPrice(rs.getInt("Price"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return b;
	}

	 
	public void updateBook(Books book) {
		// TODO Auto-generated method stub
		DBUtil util = new DBUtil();
		Connection conn = util.getConnection();
		Books b = null;
		String sql = "update Book set bookName=?,price=?,bookId=?";
		
		try {
			b=new Books();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, b.getBookName());
			pstmt.setDouble(2, b.getPrice());
			pstmt.setInt(3, b.getBookId());
			pstmt.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void addBook(Books book) {
		// TODO Auto-generated method stub
		DBUtil util = new DBUtil();
		Connection conn = util.getConnection();
		 System.out.println(conn);
		String sql = 
	    "insert into Book(bookId,bookName,price) values(?,?,?)";
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, book.getBookId());
			pstmt.setString(2, book.getBookName());
			pstmt.setDouble(3,book.getPrice());
			pstmt.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	 

	
	public void deleteBookByName(String name) {
		// TODO Auto-generated method stub
		DBUtil util = new DBUtil();
		Connection conn = util.getConnection();
		String sql = "delete from Book where bookName = ? ";
		try {
			PreparedStatement  pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, name);
			pstmt.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}

DBUtil.java:(分享了两种常用的数据库连接方式,大家可以自行选用哦!)

多插一嘴:如果连接数据库老是报classnotfundException 可以查看我的另一篇博文寻找解决方法!

package Beans;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {

	 
	public Connection getConnection() {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			return DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?serverTimezone=UTC","root","zxc123456");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	 
	
	public void closeConnection(Connection conn) {
		
		if(conn!=null)
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	public Connection openConnection() {
		Properties prop = new Properties();
		String driver = null;
		String url = null;
		String username = null; 
		String password = null;
		try {
			prop.load(
					this.getClass().getClassLoader().getResourceAsStream(
							"DBconfig.properties"));
			driver = prop.getProperty("driver");
			url = prop.getProperty("url");
			username = prop.getProperty("username");
			password = prop.getProperty("password");
			Class.forName(driver);
			return DriverManager.getConnection(url,username,password);
					  
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	
}

 home.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="Beans.DAOImpl"%>
<%@ page import="Beans.Books"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Operation</title>
<script>
            function confirmDelete() {
                if (confirm("确定删除吗?")) {
                    return true;
                } else {
                    return false;
                }
            }
            window.onload = initAll;
            function initAll() {
                //alert('init');
                var delEl = document.getElementsByClassName("da");
                for (var i = 0; i < delEl.length; i++) {
                    delEl[i].onclick = confirmDelete;
                }
            }
        </script>

</head>
<body>
<h2>书籍信息管理</h2>
<%
 DAOImpl dao = new DAOImpl();
List<Books> list = new ArrayList();
list=dao.findAllBooks();

%>
<form action="doselect.jsp" method="post">
<div>
<input type="text" name="inputName">
<input type="submit" value="查询">
</div>
<hr border="1">
</form>
<jsp:useBean id="book" class="Beans.Books"/>
<table border="1">
<tr>
<th>书籍编号</th>
<th>名称</th>
<th>价格</th>
<th>操作</th>
</tr>
<%

	for(Books b:list){
		%>
		<tr align="center">
		<td><%=b.getBookId() %></td>
		<td><%=b.getBookName() %></td>
		<td><%=b.getPrice() %></td>
		<td><a href="update.jsp?id=<%=b.getBookId()%>">修改</a> | <a class="da" href="dodelete.jsp?name=<%=b.getBookName()%>">删除</a></td>
		</tr>
		<%
	}

	

%>
</table>
<br>
<a href="insert.jsp">添加书籍</a>
</body>
</html>

insert.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert</title>
</head>
<h2>添加书籍!</h2>
<body>
<%request.setCharacterEncoding("utf-8"); %>
 <form action="doInsert.jsp" method="post">
 <div>
 	<label for="">编号:</label>
 	<input type="number" name="bookId" id="id">
 </div>
 <div>
 	<label for="">书名:</label>
 	<input type="text" name="bookName" id="book">
 </div>
 <div>
 	<label for="">价格:</label>
 	<input type="number" name="price" id="price">
 </div>
 <div>
 	 
 	<input type="submit" name="s" value="提交">
 </div>
 
 </form>

</body>
</html>

doInsert.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="Beans.DAOImpl"%>
<%@ page import="Beans.Books"%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
int id=Integer.parseInt(request.getParameter("bookId").toString());
String name=request.getParameter("bookName").toString();
double price = Double.valueOf(request.getParameter("price").toString());

%>
<%request.setCharacterEncoding("utf-8"); %>
<jsp:useBean id="book" class="Beans.Books" scope="page">
<jsp:setProperty name="book" property="bookId" value="<%=id%>" />
<jsp:setProperty name="book" property="bookName" value="<%=name%>" />
<jsp:setProperty name="book" property="price" value="<%=price%>" />
</jsp:useBean>

<%
DAOImpl dao = new DAOImpl();
dao.addBook(book);
%>

<jsp:forward page="insert.jsp"/>

</body>
</html>

update.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>update</title>
</head>
<body>
<h2>修改书籍信息</h2>
<form action="doUpdate.jsp" method="post">
<div>
<label for="">编号:</label>
<input type="number" name="id"  value="<%=Integer.parseInt(request.getParameter("id").toString()) %>" >
</div>
<div>
<label for="">书名:</label>
<input type="text" name="book">
</div>
<div>
<label for="">价格:</label>
<input type="number" name="price">
</div>
<div>
<input type="submit" value="提交">
</div>

</form>
</body>
</html>

doUpdate.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="Beans.DAOImpl"%>
<%@ page import="Beans.Books"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
int id = Integer.parseInt(request.getParameter("id").toString());
String name= request.getParameter("book").toString();
double price = Double.valueOf(request.getParameter("price"));
%>
<jsp:useBean id="book" class="Beans.Books"/>
<jsp:setProperty name="book" property="bookId" value="<%=id%>"/>
<jsp:setProperty name="book" property="bookName" value="<%=name %>"/>
<jsp:setProperty name="book" property="price" value="<%=price %>"/>

<%
DAOImpl dao = new DAOImpl();
dao.updateBook(book);
%>

<jsp:forward page="update.jsp"/>
</body>
</html>

doselect.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="Beans.DAOImpl"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>select</title>
</head>
<body>
<jsp:useBean id="b" class="Beans.Books"/>
<%
String bookname=request.getParameter("inputName").toString();
DAOImpl dao = new DAOImpl();
b=dao.findBookByName(bookname);
%>
<jsp:setProperty property="bookId" name="b" value="<%=b.getBookId() %>"/>
<jsp:setProperty property="bookName" name="b" value="<%=b.getBookName() %>"/>
<jsp:setProperty property="price" name="b" value="<%=b.getPrice() %>"/>
<table border="1">
<tr>
<th>书籍编号</th>
<th>书名</th>
<th>价格</th>
<th>操作</th>
</tr>
<%
if(b!=null){
	

%>
<tr align="center">
<td>
<jsp:getProperty property="bookId" name="b"/>
</td>
<td>
<jsp:getProperty property="bookName" name="b"/>
</td>
<td>
<jsp:getProperty property="price" name="b"/>
</td>
<td><a href="update.jsp">修改</a>|<a href="delete.jsp">删除</a></td>
</tr>
<%
}
%>
</table>

</body>
</html>

dodelete.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="Beans.DAOImpl"%>
<%@ page import="Beans.Books"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>delete</title>
</head>
<body>
<%
 
DAOImpl dao = new DAOImpl();
dao.deleteBookByName(request.getParameter("name"));
%>

<jsp:forward page="home.jsp"/>
</body>
</html>

写给自己:

  • <a href="update.jsp?id=<%=b.getBookId()%>">修改</a>中可以设id,name 等各种根据需要的,这里面的id也是一个页面传递,相当于一层过滤了,在另一页面也是使用request.getParameter("id")来获取。同时,这个页面传值应该是get请求(URL中会显示?id=)
  • <jsp:useBean id="book" class="Beans.Books"/>相当于新建了一个对象实例,同时这个对象book也可以在页面中使用
  • 表单传值乱码的问题还没有有效解决。。。(或许是浏览器不同吧)

 掉坑也要弧线!!!!

 

发布了11 篇原创文章 · 获赞 19 · 访问量 626

猜你喜欢

转载自blog.csdn.net/z_x_c_/article/details/105207851