JavaWeb 实现基础增删改查 CRUD

版权声明:分享不为别的,只为交个朋友。QQ交流群:865061230 https://blog.csdn.net/Sirius_hly/article/details/84640838

1.数据库表如下

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) NOT NULL,
  `note` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

在这里插入图片描述

2.项目的目录结构

5 个后端文件和 1 个前端文件。
controller 控制层,对业务逻辑的处理,响应给前端页面。
dao 数据接口层
entity 实体
impl 数据接口的实现,CRUD 语句
main.jsp 前端代码

在这里插入图片描述

简单前端页面,完整后端功能。
在这里插入图片描述

3.完整代码

实体类 Employee

/**
 * @author :hly
 * @github :https://github.com/huangliangyun
 * @blog :blog.csdn.net/Sirius_hly
 * @date :2018/11/29
 */
public class Employee {
    private int id;
    private String name;
    private String note;

    public Employee() {
    }

    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 String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", note='" + note + '\'' +
                '}';
    }
}

数据库连接类 DBConnection

package com.hly.jsp.javaWeb.dao;

import java.sql.*;

/**
 * @author :hly
 * @github :https://github.com/huangliangyun
 * @blog :blog.csdn.net/Sirius_hly
 * @date :2018/10/31
 */
public class DBConnection {

    private static final String driverName = "com.mysql.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/testDB?useUnicode=true&characterEncoding=UTF-8";
    private static final String user = "root";
    private static final String password = "roof";
    private static Connection connection = null;

    /*static {
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException e) {
            System.out.println("连接失败"+e.getMessage());
        }
    }
*/
    public static Connection getConnection() throws SQLException {
        try {
            Class.forName(driverName);
            connection = DriverManager.getConnection(url, user, password);;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void close(ResultSet rs, Statement st, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (st != null) {
                    st.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

EmployeeDao 数据接口层

package com.hly.jsp.javaWeb.dao;
import com.hly.jsp.javaWeb.entity.Employee;
import java.util.List;

/**
 * @author :hly
 * @github :https://github.com/huangliangyun
 * @blog :blog.csdn.net/Sirius_hly
 * @date :2018/11/29
 */
public interface EmployeeDao {
    //C
    public int add(Employee employee);
    //R
    public List<Employee> selectAll();
    public List<Employee> query(String name);
    //U
    public int  update(Employee employee);
    //D
    public int delete (int id);

}

dao 层实现类 EmployeeDaoImpl,SQL 语句的实现

package com.hly.jsp.javaWeb.impl;
import com.hly.jsp.javaWeb.dao.DBConnection;
import com.hly.jsp.javaWeb.dao.EmployeeDao;
import com.hly.jsp.javaWeb.entity.Employee;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author :hly
 * @github :https://github.com/huangliangyun
 * @blog :blog.csdn.net/Sirius_hly
 * @date :2018/11/29
 */
public class EmployeeDaoImpl implements EmployeeDao {

    //增
    @Override
    public int add(Employee employee) {

        try {
            Connection con = DBConnection.getConnection();
            String sql = "insert into employee(name,note) values(?,?)";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, employee.getName());
            ps.setString(2, employee.getNote());
            ps.executeUpdate();
            DBConnection.close(null,ps,con);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 1;
    }

    //查全部
    @Override
    public List<Employee> selectAll() {

        List<Employee> list = new ArrayList<>();
        Employee employee = null;
        try {
            Connection con = DBConnection.getConnection();
            String sql = "select id,name,note from employee";
            PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                employee = new Employee();
                employee.setId(rs.getInt(1));
                employee.setName(rs.getString(2));
                employee.setNote(rs.getString(3));
                list.add(employee);
            }
            DBConnection.close(rs,ps,con);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    //根据 id 查
    @Override
    public List<Employee> query(String name) {

        Employee employee = null;
        List<Employee> list = new ArrayList<>();

        try {
            Connection con = DBConnection.getConnection();
            String sql = "select id,name,note from employee where name like ?";
            PreparedStatement ps = con.prepareStatement(sql);
            //模糊查询
            ps.setString(1,"%"+name+"%");
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                employee = new Employee();
                employee.setId(rs.getInt(1));
                employee.setName(rs.getString(2));
                employee.setNote(rs.getString(3));
                list.add(employee);
            }
            DBConnection.close(rs,ps,con);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    //更新
    @Override
    public int update(Employee employee) {

        try {
            Connection con = DBConnection.getConnection();
            String sql = "update employee set name = ?,note = ? where id = ?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1,employee.getName());
            ps.setString(2,employee.getNote());
            ps.setInt(3,employee.getId());
            ps.executeUpdate();
            DBConnection.close(null,ps,con);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 1;
    }

    //删除
    @Override
    public int delete(int id) {
        try {
            Connection con = DBConnection.getConnection();
            String sql = "delete from employee where id = ?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setInt(1,id);
            ps.executeUpdate();
            DBConnection.close(null,ps,con);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 1;
    }
}

控制层 Servlet

EmployeeServlet

package com.hly.jsp.javaWeb.controller;

import com.hly.jsp.javaWeb.dao.EmployeeDao;
import com.hly.jsp.javaWeb.entity.Employee;
import com.hly.jsp.javaWeb.impl.EmployeeDaoImpl;

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.lang.reflect.Method;
import java.util.List;
/**
 * @author :hly
 * @github :https://github.com/huangliangyun
 * @blog :blog.csdn.net/Sirius_hly
 * @date :2018/11/28
 */

@WebServlet(urlPatterns = { "*.do" })
public class EmployeeServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        doGet(request, response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        String url = request.getRequestURI();
        String methodName = url.substring(url.lastIndexOf("/")+1, url.lastIndexOf("."));
        Method method = null;
        try {
            // 使用反射机制获取在本类中声明了的方法
            method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 执行方法
            method.invoke(this, request, response);
        } catch (Exception e) {
            throw new RuntimeException("调用方法出错");
        }
    }

    //增加
    public void addEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Employee employee = new Employee();
        employee.setName(request.getParameter("addName"));
        employee.setNote(request.getParameter("addNote"));
        EmployeeDao employeeDao = new EmployeeDaoImpl();
        employeeDao.add(employee);
        selectAllEmp(request,response);
    }

    //查找全部
    public void selectAllEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EmployeeDao employeeDao = new EmployeeDaoImpl();
        List<Employee> list = employeeDao.selectAll();
        request.setAttribute("list", list);
        request.getRequestDispatcher("/javaWeb/manage/main.jsp").forward(request, response);
    }

    //模糊查询
    public void selectByEmpName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("selectName");
        EmployeeDao employeeDao = new EmployeeDaoImpl();
        List<Employee> list = employeeDao.query(name);
        System.err.println("list:"+list);
        request.setAttribute("list", list);
        request.getRequestDispatcher("/javaWeb/manage/main.jsp").forward(request, response);
    }

    //更新数据
    public void updateEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Employee employee = new Employee();
        employee.setId(Integer.parseInt(request.getParameter("updateId")));
        employee.setName(request.getParameter("updateName"));
        employee.setNote(request.getParameter("updateNote"));
        System.err.println(employee);
        EmployeeDao employeeDao = new EmployeeDaoImpl();
        employeeDao.update(employee);
        selectAllEmp(request,response);
    }

    //删除
    public void deleteEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String deleteId = request.getParameter("deleteId");
        EmployeeDao employeeDao = new EmployeeDaoImpl();
        employeeDao.delete(Integer.parseInt(deleteId));
        selectAllEmp(request,response);
    }
}

前端代码 main.js

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>main</title>
    <style>
        a, a:focus {
            text-decoration: none;
        }
    </style>
</head>
<body>

<a href="selectAllEmp.do">点击查询所有用户信息</a><br/>

<form action="selectByEmpName.do">
    <input type="text" name="selectName" placeholder="请输入名字">
    <input type="submit" value="模糊查询">
</form>

<form action="addEmp.do">
    <input type="text" name="addName" placeholder="请输入姓名">
    <input type="text" name="addNote" placeholder="请输入Note">
    <input type="submit" value="添加">
</form>

<form action="updateEmp.do">
    <input type="text" placeholder="需要修改的id"name="updateId" >
    <input type="text" placeholder="需要修改的name" name="updateName">
    <input type="text" placeholder="需要修改的note" name="updateNote">
    <input type="submit" value="修改">
</form>

<table border="1" cellpadding="3" cellspacing="0" width="400">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>note</th>
        <th>delete</th>
    </tr>
    <c:forEach var="e" items="${list}">
        <tr>

            <td>${e.id}</td>
            <td>${e.name}</td>
            <td>${e.note}</td>
            <td><a href="deleteEmp.do?deleteId=${e.id}">删除</a></td>
        </tr>
    </c:forEach>
</table>

<script type="javascript">

</script>
</body>
</html>

我的 Github:Github
个人网站: 天狼星的博客
代码下载:https://download.csdn.net/download/sirius_hly/10817983

猜你喜欢

转载自blog.csdn.net/Sirius_hly/article/details/84640838
今日推荐