MySql+jsp+Servlet+Bean,简单实现MVC

基础环境

MySql5.7 Tomca8 IDE

数据库名 book

字段名长度类型约束
id10int主键自增
name10varchar
price10float
time0date
category20varchar
  1. 运行效果
    在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
2. 项目目录
注意:红色划线的可以忽略不看
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210515211210853.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTM5Nzc4NQ==,size_16,color_FFFFFF,t_7
3. Util包下面DButil连接数据库的工具类

package util;

import java.sql.DriverManager;
import java.sql.ResultSet;

import java.sql.PreparedStatement;

import java.sql.Connection;


public class DButil {


public static  Connection getConnection()
{
	 String dbName="root";
	 String dbPassword="123456";
	//驱动程序名
	 String jdbcName="com.mysql.jdbc.Driver";
	//URL指向要访问的数据库名book
	 String DBUrl="jdbc:mysql://localhost:3306/book";
	 Connection connection=null;
	try {
		//加载驱动
		Class.forName(jdbcName);
	    connection=DriverManager.getConnection(DBUrl, dbName, dbPassword);
		System.out.println("数据库连接成功");
	} catch (Exception e) {
		// TODO: handle exception
		System.out.println("数据连接失败");
		e.printStackTrace();
	}

	return connection;
}
//关闭数据库
public static void close(Connection conn,PreparedStatement ps,ResultSet rs)
{ try {
	if(conn!=null)
	{
		conn.close();
	}
} catch (Exception e) {
	// TODO: handle exception
	e.printStackTrace();
}
try {
	if(ps!=null)
	{
		ps.close();
	}
} catch (Exception e) {
	// TODO: handle exception
	e.printStackTrace();
}
try {
	if(rs!=null)
	{
		rs.close();
	}
} catch (Exception e) {
	// TODO: handle exception
	e.printStackTrace();
}
}
public static void main(String[] args) {
	DButil.getConnection();
}
}

  1. bean包的Book类
package bean;


	public class Book {
	private int id;
	private String name;
	private float price;
	private String time;
	private String category;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public String getTime() {
		return time;
	}
	public void setTime(String date) {
		this.time = date;
	}
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}

}

  1. 增删改查接口BookService.java
 package dao;
import bean.*;
import java.util.*;
public interface BookService {
List<Book> list();
boolean delBook(Integer id);
boolean addBook(Book add);
boolean updateBook(Book update);
}
  1. Dao包中BookDao实现增删改查操作BookDao.java
package dao;

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

import java.sql.PreparedStatement;

import bean.Book;
import util.DButil;
import dao.BookService;


public class BookDao implements BookService {
public List<Book> list(){
	 List<Book> books=new ArrayList<Book>();
	 
	 Connection conn=DButil.getConnection();
	 String  sql="select * from book";
	 PreparedStatement ps=null;//查询和更新数据
	 ResultSet rs=null;//结果集,存储数据,不能来回滚动,所以用它的next()方式读取下一行
	 try {
		ps=conn.prepareStatement(sql);
		rs=ps.executeQuery();
		while(rs.next())
		{
			Book book=new Book();
			book.setId(rs.getInt(1));
			book.setName(rs.getString(2));
			book.setPrice(rs.getFloat(3));
			book.setTime(rs.getString(4));
			book.setCategory(rs.getString(5));
			//将读取的数据存入集合中
			books.add(book);
		}
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}finally {
		DButil.close(conn, ps, rs);
	}
	return books;
}
//删除图书
@Override
public boolean delBook(Integer id) {
	// TODO Auto-generated method stub
	Connection conn=DButil.getConnection();
	String sql="delete from book where id=?";
	PreparedStatement ps=null;
	int count=0;
    try {
		ps=conn.prepareStatement(sql);
		ps.setInt(1, id);
		count=ps.executeUpdate();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		DButil.close(conn, ps,null);
	}
    //判断是否删除成功
    if(count>0)
    {
    	return true;
    }else
    {
    	return  false;
    }
}
@Override
public boolean addBook(Book add) {
	// TODO Auto-generated method stub
	//1.连接数据库
	Connection conn=DButil.getConnection();
	//2.查询语句
	String sql="insert into book (name,price,time,category) values(?,?,?,?)";
	//3.初始化PreparedStatement
	PreparedStatement ps=null;
	//4.影响的行数
	int count=0;
	try {
		//建立查询命令
		ps=conn.prepareStatement(sql);
		//BookService接口中的add方法传入的值
		ps.setString(1, add.getName());
		ps.setFloat(2, add.getPrice());
		ps.setString(3, add.getTime());
		ps.setString(4, add.getCategory());
		count=ps.executeUpdate();
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}finally {
		DButil.close(conn, ps, null);
	}
	//判断是否添加成功
	if(count>0)
	{
		return true;
	}else{
		
		return false;
	}
	
}
@Override
public boolean updateBook(Book update) {
	// TODO Auto-generated method stub
	//建立数据库连接
	Connection conn=DButil.getConnection();
	//更新语句
	String sql="update book set name=?,price=?,time=?,category=? where id=?";
	PreparedStatement ps=null;
	int count=0;
	try {
		//这个必须写try里面 否者报错
		ps=conn.prepareStatement(sql);
		//获取数据
		ps.setInt(5, update.getId());
		ps.setString(1, update.getName());
		ps.setFloat(2, update.getPrice());
		ps.setString(3, update.getTime());
		ps.setString(4, update.getCategory());
		count=ps.executeUpdate();
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
	finally {
		DButil.close(conn, ps, null);
	}
	//判断是否更新成功
	if(count>0)
	{
		return true;
	}else
	{
		return false;
	}
	}
	
	public boolean updatePrice(Book update) {
		// TODO Auto-generated method stub
		//建立数据库连接
		Connection conn=DButil.getConnection();
		//更新语句
		String sql="update book set price=? where id=?";
		PreparedStatement ps=null;
		int count=0;
		try {
			//这个必须写try里面 否者报错
			ps=conn.prepareStatement(sql);
			//获取数据
			ps.setInt(2, update.getId());
			ps.setFloat(1, update.getPrice());
			count=ps.executeUpdate();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally {
			DButil.close(conn, ps, null);
		}
		//判断是否更新成功
		if(count>0)
		{
			return true;
		}else
		{
			return false;
		
}
	}

}

  1. Servlet包
    BookAddServlet.java 添加图书,这里面美中不足的是把时间改成String类型接收数据了,但是网页和数据库依然是date类型
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 bean.Book;		
import dao.BookDao;
import dao.BookService;
@WebServlet("/bookAddServlet")
public class BookAddServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

      public void doGet(HttpServletRequest request,HttpServletResponse response ) throws ServletException, IOException
      {
    	  doPost(request, response);
      }
      public void doPost(HttpServletRequest request,HttpServletResponse response ) throws ServletException, IOException
      {
    	  //获取addbook.jsp的数据
        String name=request.getParameter("name");
        Float price=Float.parseFloat(request.getParameter("price"));
        String time=request.getParameter("date");
//        String datetime = request.getParameter("date");//获取表单信息
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");//设置为指定格式     
       // Date time = sdf.format(datetime);
//        System.out.println(time);
//		try {
// 			time = sdf.parse(datetime);
//		} catch (ParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
        String category=request.getParameter("category");
        //BookService 接口 BookDao增删改查
        System.out.println(category);
        BookService bookService=new BookDao();
//        System.out.println(time);
        Book add=new Book();
        add.setName(name);
        add.setPrice(price);
        add.setTime(time);
        add.setCategory(category);
       if(bookService.addBook(add))
       {
    	   response.sendRedirect("ListBook.jsp");
       }else
       {
    	   response.sendRedirect("ListBook.jsp");
       }
      }	
     
}

  1. BookDelServlet.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 dao.BookDao;
import dao.BookService;

/**
 * Servlet implementation class BookDelServlet
 */
@WebServlet("/BookDelServlet")
public class BookDelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookDelServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
    	doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String id=request.getParameter("id");
		BookService bookService=new BookDao();
		if(bookService.delBook(Integer.parseInt(id)))
				{
		     	response.sendRedirect("ListBook.jsp");
				}else
				{
					response.sendRedirect("ListBook.jsp");
				}
	}

}

9.BookListServlet.java 显示图书信息

package servlet;

import java.io.IOException;
import java.util.List;

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 javax.servlet.http.HttpSession;

import bean.Book;
import dao.BookDao;
import dao.BookService;

/**
 * Servlet implementation class BookListServlet
 */
@WebServlet("/BookListServlet")
public class BookListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
         BookService bookService = new BookDao();
		
		List<Book> books = bookService.list();
//		HttpSession session = request.getSession();
//		session.setAttribute("bookList", books);

		request.setAttribute("bookList", books);
		request.getRequestDispatcher("ListBook.jsp").forward(request, response);
	}

}

10.这里只对价格更新数据,美中不足没有更新整个数据,但是Dao,和接口中都有对整个表更新的操作,大家可以自行添加Servlet、Jsp页面进行数据的更新即可

package servlet;

import bean.Book;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
 
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 dao.BookDao;
import dao.BookService;
 
/**
 1. Servlet implementation class UpdateServlet
 */
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		 int id = Integer.valueOf(request.getParameter("id"));
		     Float price = Float.valueOf(request.getParameter("price"));
		     BookDao bookServlce=new BookDao();
	          Book update =new Book();
	          update.setPrice(price);
	          update.setId(id);
	       if(bookServlce.updatePrice(update))
	       {
	    		// 重定向到FindServlet
	   		response.sendRedirect("BookListServlet");
	       }else
	       {
	      		response.sendRedirect("BookListServlet");
	       }
	
 
	}
 
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
 
}
  1. jsp页面
    显示列表 ListBook.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<%@page import="java.util.List"%>
<%@page import="bean.Book"%>
<%@page import="dao.BookService"%>
<%@page import="dao.BookDao"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>所有图书信息</title>
<style type="text/css">
td {
	font-size: 12px;
}
 
h2 {
	margin: 0px
}
</style>
<script type="text/javascript">
	function check() {
	    var price = document.getElementById("price");
			if (price.value == ""||price.value==null) {
				alert("请输入更新价格!");
				return false;
			}
			if (isNaN(price.value)) {
				alert("格式错误!");
				return false;
			}
			return true;
	}
</script>
 
 
</head>
<body>
	<table align="center" width="450" border="1" height="180"
		bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1">
		<tr bgcolor="white">
			<td align="center" colspan="7">
				<h2>所有图书信息</h2>
			</td>
		</tr>
		<tr align="center" bgcolor="#e1ffc1">
			<td><b>ID</b></td>
			<td><b>图书名称</b></td>
			<td><b>价格</b></td>
			<td><b>出版时间</b></td>
			<td><b>出版类型</b></td>
			<td><b>修改</b></td>
			<td><b>删除</b></td>
		</tr>
		<%
			// 获取图书信息集合
			   BookService bookService = new BookDao();
		
		    List<Book> list = bookService.list();
			//List<Book> list = (List<Book>) request.getAttribute("bookList");
			// 判断集合是否有效
			if (list == null || list.size() < 1) {
				out.print("没有数据!");
			} else {
				// 遍历图书集合中的数据
				for (Book book : list) {
		%>
		<tr align="center"  bgcolor="white">
			<td><%=book.getId()%></td>
			<td><%=book.getName()%></td>
			<td><%=book.getPrice()%></td>
			<td><%=book.getTime() %></td>
			<td><%=book.getCategory()%></td>
			<td >
				<form style="align:center;  background-color: gray" action="UpdateServlet" method="post"
					onsubmit="return check();">
					 <input type="hidden" name="id" value="<%=book.getId()%>">
					 <input	type="text"  id="price" name="price" size="3">
				     <input type="submit" value="更新价格">
				</form>
			</td>
		    <td>
		    <a href="BookDelServlet?id=<%=book.getId()%>"  onclick="javascript:del()">删除</a>
		    <script type="text/javascript" language="javascript">
    	 function del(){
    		if(!confirm("确认要删除吗")){
    			window.event.returnValue = false;
    		}
    	}
    </script>
		    </td>
 
 
		</tr>
		<%
			}
			}
		%>
	</table>
	<h2 align="center">
		<a href="addBook.jsp">返回添加图书信息页面</a>
		 
	</h2>
 
</body>
</html>

运行结果:
在这里插入图片描述

  1. 添加页面 addBook.jsp
   <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>添加图书信息</title>
   
 
<script type="text/javascript">
	function checkBook() {
	    var name = document.getElementById("name");
	    var price = document.getElementById("price");
	    var category = document.getElementById("category");
			if (name.value == ""||name.value==null) {
				alert("图书名称不能为空");
				return false;
			}
 
			if (price.value == "") {
				alert("图书价格不能为空");
				return false;
			}
 
			if (category.value == "") {
				alert("类型不能为空");
				return false;
			}
 
		}
	
</script>
  </head>
  
  <body>
    <form action="bookAddServlet" method="post" onsubmit="return cleck1();">
   
          
            <div align="center" border="1"  width="450" bgcolor="blue" bordercolor="bule">
              <table  align="center" width="450" border="1" height="180">
              <tr bgcolor="white">
			<td align="center" colspan="2">
				<h2>添加图书信息</h2>
			</td>
		</tr>
		<tr align="center" bgcolor="#1E90FF"><td>图书名称:</td><td><input id="name" type="text" name="name"/></td></tr> 
    	<tr align="center" bgcolor="#1E90FF"><td>图书价格:</td><td><input id="price" type="text" name="price"/></tr></td>
    	<tr align="center" bgcolor="#1E90FF"><td>出版日期:</td><td><input type="date" name="date"/></tr></td>
    	<tr align="center" bgcolor="#1E90FF"><td>出版类型:</td><td><input id="category" type="text" name="category"/></td></tr>
    <!-- 两种form验证 一种是 form onsubmit 一种button	<tr align="center" bgcolor="#1E90FF"> <td  align="center"   colspan="2"><input type="submit"  value="添加"/></tr> -->
    	<tr align="center" bgcolor="#1E90FF"> <td  align="center"   colspan="2"><input type="button" value="添加"  onclick = "checkBook();" /></tr>
    	
		</table>
		</div>
    </form>
    <h2 align="center">
	<a href="BookListServlet">查询图书信息</a>
</h2>
  </body>
</html>


运行结果
在这里插入图片描述

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐