博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaWeb 实现基础增删改查 CRUD
阅读量:4104 次
发布时间:2019-05-25

本文共 11418 字,大约阅读时间需要 38 分钟。

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
selectAll(); public List
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
selectAll() { List
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
query(String name) { Employee employee = null; List
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
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
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" %>    main    点击查询所有用户信息
id name note delete
${e.id} ${e.name} ${e.note} 删除

ABOUT

公众号:【星尘Pro】

github:

推荐阅读

你可能感兴趣的文章
2016——个人年度总结
查看>>
2017——新的开始,加油!
查看>>
【Python】学习笔记——-6.2、使用第三方模块
查看>>
【Python】学习笔记——-7.0、面向对象编程
查看>>
【Python】学习笔记——-7.1、类和实例
查看>>
【Python】学习笔记——-7.2、访问限制
查看>>
【Python】学习笔记——-7.3、继承和多态
查看>>
【Python】学习笔记——-7.4、获取对象信息
查看>>
【Python】学习笔记——-7.5、实例属性和类属性
查看>>
Linux设备模型(总线、设备、驱动程序和类)之四:class_register
查看>>
git中文安装教程
查看>>
虚拟机 CentOS7/RedHat7/OracleLinux7 配置静态IP地址 Ping 物理机和互联网
查看>>
弱类型、强类型、动态类型、静态类型语言的区别是什么?
查看>>
Struts2技术内幕图书 转载
查看>>
Java异常分类
查看>>
项目中的jackson与json-lib使用比较
查看>>
Jackson Tree Model Example
查看>>
j2ee-验证码
查看>>
日志框架logj的使用
查看>>
js-高德地图规划路线
查看>>