Jsp+Servlet+JDBC(c3p0连接池)+Mysql实现增删改查

一、 项目介绍

1、采用MVC架构模式中,JSP充当视图(view)而Servlet适合充当控制器(controller)。
2、项目开发工具:

   (1) jdk1.8.0_92
   (2) apache-tomcat-8.5.39
   (3) mysql-5.5.45-winx64
   (4) Navicat_for_MySQL_11.0.10
   (5) IDEA-2019.3.4

3、所需jar包:

   (1) c3p0-0.9.1.2.jar
   (2) jstl-1.2.jar
   (3) mysql-connector-java-5.1.6.jar

4、项目目录结构

Jsp+Servlet+JDBC(c3p0连接池)+Mysql实现增删改查_第1张图片

5、数据库信息

Jsp+Servlet+JDBC(c3p0连接池)+Mysql实现增删改查_第2张图片

6、项目截图(只展示部分功能截图)

Jsp+Servlet+JDBC(c3p0连接池)+Mysql实现增删改查_第3张图片

二、源码

1、c3p0-config.xml (此配置文件直接是在src文件夹下)
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<!-- 我们希望在配置文件中,出现链接的参数信息 -->
<!--	1、配置默认数据源-->
	<default-config>
		<!-- name 属性定义 链接参数的key 标签的内容 代表值-->
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<!-- 采用了简写形式,三个/-->
		<property name="jdbcUrl">jdbc:mysql:///myschool
		<property name="user">root</property>
		<property name="password">root</property>
	</default-config>
</c3p0-config>

注意:MySQL 8.0 以上版本 数据库驱动发送变化,配置文件使用下面的

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<!-- 我们希望在配置文件中,出现链接的参数信息 -->
<!--	1、配置默认数据源-->
	<default-config>
		<!-- name 属性定义 链接参数的key 标签的内容 代表值-->
		<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
		<!-- 采用了简写形式,三个/-->
		<property name="jdbcUrl">jdbc:mysql:///myschool?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC
		<property name="user">root</property>
		<property name="password">root</property>
	</default-config>
</c3p0-config>
2、Jsp页面

   (1) index.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 南一
  Date: 2020/9/8
  Time: 22:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>显示所有用户信息</title>
    <%
        String path = request.getContextPath();
    %>
    <style type="text/css">
        a {
            text-decoration: none;
            border: 1px solid red;
        }

        table {
            border: 1px solid black;
            text-align: center;
            border-collapse: collapse;
        }

        tr, td {
            border: 1px solid black;
        }

    </style>
</head>
<body bgcolor="#ffe4c4">
<div align="center">
    <h3>员工明细列表</h3>
    <table>
        <tr>
            <td>序号</td>
            <td>员工编号</td>
            <td>员工姓名</td>
            <td>password</td>
            <td>update</td>
            <td>delete</td>
        </tr>
        <%
            int i = 1;
            pageContext.setAttribute("index", i);
        %>
        <c:forEach items="${requestScope.lists}" var="list">
            <tr>
                <td>${index}</td>
                <td>${list.id}</td>
                <td>${list.username}</td>
                <td>${list.password}</td>
                <td>
                    <button onclick=" location.href='UpdateUserServlet?id=${list.id}'">修改</button>
                </td>
<%--                直接通过<a>超链接标签访问DeleteUserServlet,onclick="return confirm('确定删除吗?')浏览器弹窗提醒--%>
                <td><a href="DeleteUserServlet?id=${list.id}" onclick="return confirm('确定删除吗?')">删除</a></td>
            </tr>
            <%
                i++;
                pageContext.setAttribute("index", i);
            %>
        </c:forEach>

    </table>
    <br>
    <a href="/ShowUserServlet">显示所有</a>
    <a href="add.jsp">添加</a>
    <a href="/DeleteAllUserServlet">删除所有</a>
</div>
</body>
</html>


   (2) add.jsp

<%--
  Created by IntelliJ IDEA.
  User: 南一
  Date: 2020/9/8
  Time: 23:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加</title>
    <style type="text/css">
        a {
            text-decoration: none;
            border:1px solid red;
        }
    </style>
    <script type="text/javascript">
        function UserBlur() {
            //根据id拿到用户输入的输入框
            var _input = document.getElementById("username");
            //获取输入框的内容
            var _username = _input.value;
            //创建regExp对象
            var regExp = new RegExp("^[a-zA-Z\u4e00-\u9fa5]+$");
            //判断用户输入的名字是不是符合我们的校验规则
            if (regExp.test(_username)) {
                var _input = document.getElementById("UserSpan");
                _input.innerHTML = "";
            } else {
                var _input = document.getElementById("UserSpan");
                _input.innerHTML = "必须是字母汉字";
            }
        }

    </script>
</head>
<body bgcolor="#7fffd4">
<h4 align="">添加页面</h4>
<%--${pageContext.request.contextPath}获取项目名字--%>
<form method="post" action="/AddUserServlet">
    用户名:
    <input type="text" name="username" id="username" onblur="UserBlur();"/><font color="red">*</font>
    <font color="red"><span id="UserSpan"></span></font><br>&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="password"/><font color="red">${requestScope.p}</font><br>
    <br>
    <input type="submit" value="添加"/>
    <input type="reset" value="重置"/>
    <a href="http://localhost:8080/ShowUserServlet">返回</a>
</form>
</body>
</html>

   (3) update.jsp

<%--
  Created by IntelliJ IDEA.
  User: 南一
  Date: 2020/9/9
  Time: 21:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改页面</title>
    <style type="text/css">
        a {
            text-decoration: none;
            border: 1px solid red;
        }
    </style>
</head>
<body>
<%--    获取路径--%>
<form action="/FinalUpdateServlet" method="get">
    用户id:<input type="text" name="id" id="id" value="${map.id}" readonly="readonly"/>
    <font color="red">用户id不允许修改</font><br>
    用户名:
    <input type="text" name="username" id="username" value="${map.username}"/><br>&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="password" id="password" value="${map.password}"/><br>
    <input type="submit" value="修改"/>
    <a href="http://localhost:8080/ShowUserServlet">返回</a>
</form>
</body>
</html>

3、utils工具类

   JdbcUtil.java

package com.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcUtil {
    //创建c3p0的实例,读取src下面的配置文件中default-config里面的默认数据源
    private static ComboPooledDataSource ds = new ComboPooledDataSource();

    //创建c3p0的实例,读取src下面的配置文件中named-config里面的初始数据源
//    private static ComboPooledDataSource ds1 = new ComboPooledDataSource("petshop");
    //从连接池里面获取连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    //关闭两个参数,释放资源
    public static void close(Connection conn, PreparedStatement ps) {
        try {
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            //使用连接池后,此时的close()并不是关闭链接,而是把链接放回到了连接池中
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭三个参数,释放资源
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            //使用连接池后,此时的close()并不是关闭链接,而是把链接放回到了连接池中
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

4、pojo层(实体映射层)

   User.java

package com.pojo;

public class User {
    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User() {
    }

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

5、dao层(直接与数据库进行交互的层),这里我将显示所有、增加、删除、修改的方法写在了一个java文件里

   ShowUserDaoImpl.java

package com.dao;

import com.pojo.User;
import com.utils.JdbcUtil;

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

public class ShowUserDaoImpl {
    //显示所有
    public List<User> showUser() {
        //创建连接变量,并且赋初始值为null
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        //定义list集合存对象信息
        List<User> list = new ArrayList<>();
        try {
            conn = JdbcUtil.getConnection();
            String sql = "select * from user";
            pstm = conn.prepareStatement(sql);
            rs = pstm.executeQuery();
            while (rs.next()) {
                //获取数据库的信息
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                //把查询到的信息封装到user对象中
                User resUser = new User();
                resUser.setId(id);
                resUser.setUsername(username);
                resUser.setPassword(password);
                //把user对象添加到list集合中
                list.add(resUser);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstm, rs);
        }
        return list;
    }

    //添加用户信息
    public int addDaoUser(User user) {
        //创建连接变量,并且赋初始值为null
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = JdbcUtil.getConnection();
            //因为id在MySQL中设置的是自动增长,所以赋值里面填null即可
            String sql = "insert into user(id,username,password) value (null,?,?) ";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, user.getUsername());
            pstm.setString(2, user.getPassword());
            int i = pstm.executeUpdate();
            if (i > 0) {
                return 1;
            } else {
                return 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstm);
        }
        return 0;
    }

    //删除用户
    public int deleteDaoUser(String id) {
        //创建连接变量,并且赋初始值为null
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = JdbcUtil.getConnection();
            //因为id在MySQL中设置的是自动增长,所以赋值里面填null即可
            String sql = "delete from user where id = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, id);
            int i = pstm.executeUpdate();
            if (i > 0) {
                return 1;
            } else {
                return 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstm);
        }
        return 0;
    }

    //删除所有用户信息
    public int deleteAllDaoUser() {
        //创建连接变量,并且赋初始值为null
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = JdbcUtil.getConnection();
            //因为id在MySQL中设置的是自动增长,所以赋值里面填null即可
            String sql = "delete from user";
            pstm = conn.prepareStatement(sql);
            int i = pstm.executeUpdate();
            if (i > 0) {
                return 1;
            } else {
                return 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstm);
        }
        return 0;
    }

    //先根据id去查询,用作回显
    public Map<String, Object> toUpdateDaoUser(int id) {
        //创建连接变量,并且赋初始值为null
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        //定义Map集合存对象信息
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            conn = JdbcUtil.getConnection();
            String sql = "select * from user where id = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setInt(1, id);
            System.out.println(sql);
            rs = pstm.executeQuery();
            while (rs.next()) {
                //获取数据库的信息
                int userid = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                //放到Map集合
                map.put("id", userid);
                map.put("username", username);
                map.put("password", password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstm, rs);
        }
        return map;
    }

    //最终修改
    public boolean updateUser(User user) {
        //创建连接变量,并且赋初始值为null
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = JdbcUtil.getConnection();
            String sql = "update user set username = ?,password = ? where id = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, user.getUsername());
            pstm.setString(2, user.getPassword());
            pstm.setInt(3, user.getId());
            int a = pstm.executeUpdate();
            if (a > 0) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstm);
        }
        return false;
    }
}

6、service层(业务处理层),调用dao层方法

   ServiceImpl.java

package com.service;

import com.dao.ShowUserDaoImpl;
import com.pojo.User;

import java.util.List;
import java.util.Map;

public class ServiceImpl {
    //注入dao层
    ShowUserDaoImpl addDao = new ShowUserDaoImpl();

    //显示所有用户信息
    public List<User> showAllUser() {
        return addDao.showUser();
    }

    //添加用户
    public int addUser(User user) {
        return addDao.addDaoUser(user);
    }

    //删除用户
    public int deleteUser(String id) {
        return addDao.deleteDaoUser(id);
    }

    //删除所有用户
    public int deleteAllUser() {
        return addDao.deleteAllDaoUser();
    }

    //修改之前先查询,进行回显
    public Map<String, Object> toUpdate(int id) {
        return addDao.toUpdateDaoUser(id);
    }

    //最终修改
    public boolean updateUser(User user) {
        boolean updateUser = addDao.updateUser(user);
        if (updateUser == true) {
            return updateUser;
        }
        return false;
    }
}

7、servlet层(请求控制层)

   ShowUserServlet.java

package com.controller;

import com.pojo.User;
import com.service.ServiceImpl;

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("/ShowUserServlet")
public class ShowUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //注入service层
        ServiceImpl service = new ServiceImpl();
        //调用service层方法
        List<User> list = service.showAllUser();
        //把获取到的list集合查询到的所有用户信息,写入到浏览器的request域中
        request.setAttribute("lists", list);
        //将查询到的所有用户信息转发到index.jsp页面进行显示
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }
}

   AddUserServlet.java

package com.controller;

import com.pojo.User;
import com.service.ServiceImpl;

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("/AddUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码集
        request.setCharacterEncoding("utf-8");
        //获取页面提交的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //把获取到的用户信息封装到user实体类对象中去
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        System.out.println(user);
        //调用service
        ServiceImpl userService = new ServiceImpl();
        //添加功能,要么成功要么失败,update方法如果添加成功返回>0
        int a = userService.addUser(user);
        if (a == 1) {
            //添加成功后,重定向显示所有用户的页面,这里为了直接跳到查询后的页面,直接重定向到ShowUserServlet
            response.sendRedirect("http://localhost:8080/ShowUserServlet");
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

   DeleteUserServlet.java

package com.controller;

import com.service.ServiceImpl;

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("/DeleteUserServlet")
public class DeleteUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码集
        request.setCharacterEncoding("utf-8");
        //  获取id,根据id来删除,getParameter()方法返回的是String类型
        String id = request.getParameter("id");
        //注入service层
        ServiceImpl service = new ServiceImpl();
        //调用service层的删除方法
        int a = service.deleteUser(id);
        if (a == 1) {
            //删除成功后,重定向显示所有用户的页面
            response.sendRedirect("http://localhost:8080/ShowUserServlet");
        }
    }
}

   DeleteAllUserServlet.java

package com.controller;

import com.service.ServiceImpl;

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("/DeleteAllUserServlet")
public class DeleteAllUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //注入service层
        ServiceImpl service = new ServiceImpl();
        //调用service层的删除方法
        int a = service.deleteAllUser();
        if (a == 1) {
            //删除成功后,重定向显示所有用户的页面
            response.sendRedirect("http://localhost:8080/ShowUserServlet");
        }

    }
}

   UpdateUserServlet.java

package com.controller;

import com.service.ServiceImpl;

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.Map;

//先根据id查询
@WebServlet("/UpdateUserServlet")
public class UpdateUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //修改之前先查询,用作修改的回显
        //根据id来修改
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        //注入service层
        ServiceImpl service = new ServiceImpl();
        //调用service层方法,将String类型的id强转为int类型
        Map<String, Object> map = service.toUpdate(Integer.parseInt(id));
        System.out.println(map);
        //写入浏览器
        request.setAttribute("map", map);
        //转发到update.jsp页面
        request.getRequestDispatcher("update.jsp").forward(request, response);
    }
}

   FinalUpdateServlet.java

package com.controller;

import com.pojo.User;
import com.service.ServiceImpl;

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("/FinalUpdateServlet")
public class FinalUpdateServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取页面上所有提交的参数
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //封装到user实体中
        User user = new User();
        //使用Integer.parseInt(id)将String类型的id转为Int类型
        user.setId(Integer.parseInt(id));
        user.setUsername(username);
        user.setPassword(password);
        //调用service层方法
        ServiceImpl service = new ServiceImpl();
        boolean updateUser = service.updateUser(user);
        if (updateUser == true) {
            response.sendRedirect("/ShowUserServlet");
        }
    }
}

源码,以及导入项目到自己的idea中,可以地下评论留下QQ号,看到后会及时回复,也可以加群交流,谢谢

你可能感兴趣的:(JavaWeb,java,爬虫,后端)