小型员工管理系统 1.0 绿色版(java实现版,附源码)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: 小型员工管理系统 1.0 绿色版(java实现版,附源码)

小型员工管理系统 1.0 绿色版(java实现版)

员工管理系统简介:

整个系统其实很简单,这里主要技术:idea开发工具+JSP + Struts2+ JDBC + Mysql实现
1、管理员的登录,注册,验证码功能
2、员工的增删改查,批量删除,上传文件,下载文件 其中类的设计(实体)很有参考意义。
整个系统设计的目标人群是管理者,系统的主要功能是对员工进行各种信息的操作。
主要是完成对数据库的增删改查的功能。

一. 项目整体目录结构

MVC实现,界面层(Web)主要使用jsp来动态展现数据库中的数据,业务逻辑层(servlets)使用的servlet,数据访问层(dao)主要是连接各个Servlet与数据库之前的通信,从而实现对数据库的各种操作。其中的entity包主要是封装了两个实体:管理员和员工,方便且规范对数据的操作和代码的书写。


image.png

image.png



二. 界面效果展示:

1、管理员页面

(1)管理员登录页面


image.png

(2)管理员注册页面

image.png


2、员工页面

(1)员工页面展示

页面展示完成员工的增删改查,员工资料管理系统:完成上传文件,下载文件


image.png

(2)员工更新【页面数据回显】


image.png

(3)添加员工页面


image.png

三、数据库设计

1、admin表(管理员的账号和密码)

image.png


2、user表(员工信息表)

image.png


四、核心jar包(jar包下载参见文章末尾)

image.png


五、核心代码展示:(完整代码参见文章末尾)

1、entity类


image.png

(1)Admin.java(管理员属性的实体层,这里有管理员的登录账号和密码的定义)

package com.tjcu.entity;
/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/9/27 18:48
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:管理员功能:登录  注册   退出
 */
public class Admin {
    private String id;
    private String name;
    private String password;
    public Admin() {
    }
    public Admin(String id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "Admin{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

(2)User.java(和Admin.java差不多主要是实体属性的get和set方法)

package com.tjcu.entity;
/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/9/27 18:49
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:
 */
public class User {
    private String id;
    private String username;
    private Double salary;
    private Integer age;
    public User() {
    }
    public User(String id, String username, Double salary, Integer age) {
        this.id = id;
        this.username = username;
        this.salary = salary;
        this.age = age;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Double getSalary() {
        return salary;
    }
    public void setSalary(Double salary) {
        this.salary = salary;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                ", salary=" + salary +
                ", age=" + age +
                '}';
    }
}

2、Dao层

image.png


(1)AdminDao接口

管理员功能:登录 注册 退出

package com.tjcu.dao;
import com.tjcu.entity.Admin;
/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/9/27 18:47
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:管理员功能:登录  注册   退出
 */
public interface AdminDao {
    /**
     * 登录
     * @param admin
     */
    public void insert(Admin admin);
    /**
     * 注册
     * @param name
     * @param password
     * @return
     */
    public Admin selectByNameAndPassword(String name,String password);
}

(2)AdminDao接口实现

package com.tjcu.dao.impl;
import com.tjcu.dao.UserDao;
import com.tjcu.entity.User;
import com.tjcu.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/9/27 18:56
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:员工功能:展示所有 、 添加 、 删除 、 修改
 */
public class UserDaoImpl implements UserDao {
    @Override
    public List<User> selectAll() {
        ResultSet rs = null;
        PreparedStatement pstm = null;
        Connection conn = null;
        List<User> list = new ArrayList<>();
        try {
            conn = JdbcUtils.getConnection();
            String sql = "select * from t_user;";
            pstm = conn.prepareStatement(sql);
            rs = pstm.executeQuery();
            while (rs.next()) {
                String id = rs.getString("id");
                String username = rs.getString("username");
                double salary = rs.getDouble("salary");
                int age = rs.getInt("age");
                User user = new User(id, username, salary, age);
                list.add(user);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            JdbcUtils.close(rs, pstm, conn);
        }
    }
    @Override
    public void insert(User user) {
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "insert t_user value(?,?,?,?)";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, user.getId());
            pstm.setString(2, user.getUsername());
            pstm.setDouble(3, user.getSalary());
            pstm.setInt(4, user.getAge());
            pstm.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(pstm, null);
        }
    }
    @Override
    public void delete(String id) {
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "delete from t_user where id=?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, id);
            pstm.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(pstm, null);
        }
    }
    @Override
    public User selectById(String id) {
        ResultSet rs = null;
        PreparedStatement pstm = null;
        Connection conn = null;
        User user = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "select * from t_user where id=?;";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, id);
            rs = pstm.executeQuery();
            if (rs.next()) {
                String id2 = rs.getString("id");
                String username = rs.getString("username");
                double salary = rs.getDouble("salary");
                int age = rs.getInt("age");
                user = new User(id2, username, salary, age);
            }
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            JdbcUtils.close(rs, pstm, conn);
        }
    }
    @Override
    public void update(User user) {
        PreparedStatement pstm = null;
        Connection conn = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "update t_user set  username=?,salary=?,age=? where id=?;";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, user.getUsername());
            pstm.setDouble(2, user.getSalary());
            pstm.setInt(3, user.getAge());
            pstm.setString(4, user.getId());
            System.out.println("Update+++" + user);
            pstm.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            JdbcUtils.close(pstm, null);
        }
    }
}

(3)UserDao接口

员工功能:展示所有 、 添加 、 删除 、 修改

package com.tjcu.dao;


import com.tjcu.entity.User;


import java.util.List;


/**

* @author 王恒杰

* @version 1.0

* @date 2021/9/27 18:56

* @email 1078993387@qq.com

* @Address 天津

* @Description:员工功能:展示所有 、 添加 、 删除 、 修改

*/

public interface UserDao {

   /**

    * 展示所有

    * @return

    */

   public List<User> selectAll();


   /**

    *  添加

    * @param user

    */

   public void insert(User user);


   /**

    * 删除

package com.tjcu.dao;
import com.tjcu.entity.User;
import java.util.List;
/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/9/27 18:56
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:员工功能:展示所有 、 添加 、 删除 、 修改
 */
public interface UserDao {
    /**
     * 展示所有
     * @return
     */
    public List<User> selectAll();
    /**
     *  添加
     * @param user
     */
    public void insert(User user);
    /**
     * 删除
     * @param id
     */
    public void delete(String id);
    /**
     * 回显
     * @param id
     * @return
     */
    public User selectById(String id);
    /**
     * 修改
     * @param user
     */
    public void update(User user);
}

(4)UserDao接口实现

package com.tjcu.dao.impl;
import com.tjcu.dao.AdminDao;
import com.tjcu.entity.Admin;
import com.tjcu.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/9/27 18:48
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:
 */
public class AdminDaoImpl implements AdminDao {
    @Override
    public void insert(Admin admin) {
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "insert t_admin value(?,?,?)";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, admin.getId());
            pstm.setString(2, admin.getName());
            pstm.setString(3, admin.getPassword());
            pstm.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("注册异常");
        } finally {
            JdbcUtils.close(pstm, null);
        }
    }
    @Override
    public Admin selectByNameAndPassword(String name, String password) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        Admin admin = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "select * from t_admin where name=? and password=?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, name);
            pstm.setString(2, password);
            rs = pstm.executeQuery();
            if (rs.next()) {
                admin = new Admin();
                admin.setId(rs.getString(1));
                admin.setName(rs.getString(2));
                admin.setPassword(rs.getString(3));
            }
            return admin;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("登录异常");
            throw new RuntimeException(e.getMessage());
        } finally {
            JdbcUtils.close(rs, pstm, conn);
        }
    }
}

3、service层[略,详情请参见文章末尾]


image.png

4、struts2实现Action层

image.png


(1)MyAction:管理员登录、注册 员工:增删改查

package com.tjcu.action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/10/10 20:48
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:
 */
public class DownloadAction extends ActionSupport {
    //1接收用户要下载的文件名称
    private String fileName;
    //服务器上下载文件的存储文件夹
    private String filePath;
    //服务方法用于文件下载
    public InputStream getInputStream() throws Exception {
        //根据相对路径获取下载文件的绝对路径
        String realPath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath(filePath);
        FileInputStream is = new FileInputStream(realPath + "\\" + fileName);
        System.out.println(is);
        //将读取的文件输入流直接返回到Client
        return is;
    }
    public String getFilePath() {
        return filePath;
    }
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

(2)UploadAction:上传功能

package com.tjcu.action;
import com.opensymphony.xwork2.ActionSupport;
import com.tjcu.entity.Admin;
import com.tjcu.entity.User;
import com.tjcu.service.AdminService;
import com.tjcu.service.impl.AdminServiceImpl;
import com.tjcu.service.impl.UserServieImpl;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.List;
/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/9/29 19:50
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:
 */
public class MyAction extends ActionSupport {
    private String password1;
    private String password2;
    private  String name;
    private Admin admin;
    private User user;
    private String[] isCheck;
    private String code;
    public String register(){
//        管理员注册
        if(password1.equals(password2)){
           Admin admin1= new Admin(null, name, password1);
            System.out.println(admin1);
            AdminService adminService = new AdminServiceImpl();
            adminService.register(admin1);
            return "registerOk";
        }else {
            return  "registerError";
        }
    }
    public String login() throws UnsupportedEncodingException {
//        管理员登录
        HttpServletRequest request = ServletActionContext.getRequest();
        request.setCharacterEncoding("utf-8");
        AdminService adminService = new AdminServiceImpl();
        Admin admin1 = adminService.login(admin.getName(), admin.getPassword());
        System.out.println(admin1);
        HttpSession session = request.getSession();
        String code1 = (String) session.getAttribute("code");
        if(code.equals(code1)){
            if(admin1!=null){
                System.out.println(admin1.getName());
                request.getSession().setAttribute("admin",admin.getName());
                return "loginOk";
            }else{
                return "loginError";
            }
        }else{
            return "loginError";
        }
    }
    public String userAdd(){
//        添加用户
        UserServieImpl userServie = new UserServieImpl();
        User user2 = new User(null,user.getUsername(),user.getSalary(),user.getAge());
        userServie.add(user2);
        return "useraddOk";
    }
    public String userDelete(){
//        删除用户
        UserServieImpl userServie = new UserServieImpl();
        userServie.drop(user.getId());
        System.out.println(user.getId());
        return "userDeleteOk";
    }
    public String deleteAll(){
//        批量删除用户
        UserServieImpl userServie = new UserServieImpl();
        for (String id : isCheck) {
                userServie.drop(id);
        }
        System.out.println(isCheck);
        return "dropAllOk";
    }
    public String userSelectById(){
//        根据id查用户
        UserServieImpl userServie = new UserServieImpl();
        User user1 = userServie.selectById(user.getId());
        System.out.println(user1);
        HttpServletRequest request = ServletActionContext.getRequest();
        request.setAttribute("user",user1);
        return  "userSelectOk";
    }
    public String userShow(){
//        展示用户
        HttpServletRequest request = ServletActionContext.getRequest();
        if(request.getSession().getAttribute("admin")!=null) {
            UserServieImpl userServie = new UserServieImpl();
            List<User> users = userServie.show();
            request.setAttribute("users", users);
            return "userShowOk";
        }else {
            return "userShowError";
        }
    }
    public String userUpdate(){
//        更新用户
        UserServieImpl userServie = new UserServieImpl();
        User user1 = new User(user.getId(),user.getUsername(),user.getSalary(),user.getAge());
        System.out.println("update"+user1);
        userServie.update(user1);
        return "userUpdateOk";
    }
    public String session(){
        HttpServletRequest request = ServletActionContext.getRequest();
        request.getSession().invalidate();
        return "sessionOk";
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public Admin getAdmin() {
        return admin;
    }
    public void setAdmin(Admin admin) {
        this.admin = admin;
    }
    public String getPassword1() {
        return password1;
    }
    public void setPassword1(String password1) {
        this.password1 = password1;
    }
    public String getPassword2() {
        return password2;
    }
    public void setPassword2(String password2) {
        this.password2 = password2;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String[] getIsCheck() {
        return isCheck;
    }
    public void setIsCheck(String[] isCheck) {
        this.isCheck = isCheck;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
}

(3)DownloadAction:下载功能

package com.tjcu.action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import java.io.File;
import java.io.IOException;
/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/10/10 20:27
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:
 */
public class UploadAction extends ActionSupport {
    //接收数据
    private File upload;
//    Struts2框架提供数据获取上传文件原名方式 成员变量 名字:上传文件+“FileName”
    private String uploadFileName;
//    获取当前上传文件类型 成员变量 名字:上传文件+ContentType MIMA类型 大类型/小类型
    private String uploadContentType;
    //Struts2的Action成员变量的作用
    //1、接收Client请求参数 2.替换Request作用域  3.可以通过Struts2配置文件为Action的成员变量赋值
//    可以通过Struts2配置文件为Action的成员变量赋值 String path
    private String filePath;
    @Override
    public String execute() throws Exception {
        System.out.println("文件名" + uploadFileName);
        System.out.println("文件类型" + uploadContentType);
        System.out.println(filePath);
//        可以通过相对路径获取绝对路径 ServletContetx.getRealPath("path") 通过相对路径获取绝对路径
        String realPath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath(filePath);
        System.out.println(realPath);
        FileUtils.copyFile(upload, new File(realPath +"//"+ uploadFileName));
        //跳转页面
        return SUCCESS;
    }
    public File getUpload() {
        return upload;
    }
    public void setUpload(File upload) {
        this.upload = upload;
    }
    public String getUploadFileName() {
        return uploadFileName;
    }
    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }
    public String getUploadContentType() {
        return uploadContentType;
    }
    public void setUploadContentType(String uploadContentTtpe) {
        this.uploadContentType = uploadContentTtpe;
    }
    public String getFilePath() {
        return filePath;
    }
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}

(4)ValidationCodeAction:验证码功能

package com.tjcu.action;
/**
 *  用于生成验证码图片  不提供返回页面
 * @author 86151
 */
public class ValidationCodeAction implements Action {
  private static final long serialVersionUID = 5126616339795936447L;
  private ConfigurableCaptchaService configurableCaptchaService = null;
  private ColorFactory colorFactory = null;
  private RandomFontFactory fontFactory = null;
  private RandomWordFactory wordFactory = null;
  private TextRenderer textRenderer = null;
  public void init() throws ServletException {
    configurableCaptchaService = new ConfigurableCaptchaService();
    // 颜色创建工厂,使用一定范围内的随机色
    colorFactory = new RandomColorFactory();
    configurableCaptchaService.setColorFactory(colorFactory);
    // 随机字体生成器
    fontFactory = new RandomFontFactory();
    fontFactory.setMaxSize(32);
    fontFactory.setMinSize(28);
    configurableCaptchaService.setFontFactory(fontFactory);
    // 随机字符生成器,去除掉容易混淆的字母和数字,如o和0等
    wordFactory = new RandomWordFactory();
    wordFactory.setCharacters("abcdefghkmnpqstwxyz23456789");
    wordFactory.setMaxLength(5);
    wordFactory.setMinLength(4);
    configurableCaptchaService.setWordFactory(wordFactory);
    // 自定义验证码图片背景
    MyCustomBackgroundFactory backgroundFactory = new MyCustomBackgroundFactory();
    configurableCaptchaService.setBackgroundFactory(backgroundFactory);
    // 图片滤镜设置
    ConfigurableFilterFactory filterFactory = new ConfigurableFilterFactory();
    List<BufferedImageOp> filters = new ArrayList<BufferedImageOp>();
    WobbleImageOp wobbleImageOp = new WobbleImageOp();
    wobbleImageOp.setEdgeMode(AbstractImageOp.EDGE_MIRROR);
    wobbleImageOp.setxAmplitude(2.0);
    wobbleImageOp.setyAmplitude(1.0);
    filters.add(wobbleImageOp);
    filterFactory.setFilters(filters);
    configurableCaptchaService.setFilterFactory(filterFactory);
    // 文字渲染器设置
    textRenderer = new BestFitTextRenderer();
    textRenderer.setBottomMargin(3);
    textRenderer.setTopMargin(3);
    configurableCaptchaService.setTextRenderer(textRenderer);
    // 验证码图片的大小
    configurableCaptchaService.setWidth(82);
    configurableCaptchaService.setHeight(32);
  }
  @Override
  public String execute() throws Exception {
    init();
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("image/png");
    response.setHeader("cache", "no-cache");
    HttpSession session = request.getSession(true);
    OutputStream outputStream = response.getOutputStream();
    // 得到验证码对象,有验证码图片和验证码字符串
    Captcha captcha = configurableCaptchaService.getCaptcha();
    // 取得验证码字符串放入Session
    String validationCode = captcha.getChallenge();
    session.setAttribute("code", validationCode);
    // 取得验证码图片并输出
    BufferedImage bufferedImage = captcha.getImage();
    ImageIO.write(bufferedImage, "png", outputStream);
    outputStream.flush();
    outputStream.close();
    destroy();
    return null;
  }
  public void destroy() {
    wordFactory = null;
    colorFactory = null;
    fontFactory = null;
    textRenderer = null;
    configurableCaptchaService = null;
  }
  /**
   * 自定义验证码图片背景,主要画一些噪点和干扰线
   */
  private class MyCustomBackgroundFactory implements BackgroundFactory {
    private Random random = new Random();
    @Override
    public void fillBackground(BufferedImage image) {
      Graphics graphics = image.getGraphics();
      // 验证码图片的宽高
      int imgWidth = image.getWidth();
      int imgHeight = image.getHeight();
      // 填充为白色背景
      graphics.setColor(Color.WHITE);
      graphics.fillRect(0, 0, imgWidth, imgHeight);
      // 画100个噪点(颜色及位置随机)
      for (int i = 0; i < 100; i++) {
        // 随机颜色
        int rInt = random.nextInt(255);
        int gInt = random.nextInt(255);
        int bInt = random.nextInt(255);
        graphics.setColor(new Color(rInt, gInt, bInt));
        // 随机位置
        int xInt = random.nextInt(imgWidth - 3);
        int yInt = random.nextInt(imgHeight - 2);
        // 随机旋转角度
        int sAngleInt = random.nextInt(360);
        int eAngleInt = random.nextInt(360);
        // 随机大小
        int wInt = random.nextInt(6);
        int hInt = random.nextInt(6);
        graphics.fillArc(xInt, yInt, wInt, hInt, sAngleInt, eAngleInt);
        // 画5条干扰线
        if (i % 20 == 0) {
          int xInt2 = random.nextInt(imgWidth);
          int yInt2 = random.nextInt(imgHeight);
          graphics.drawLine(xInt, yInt, xInt2, yInt2);
        }
      }
    }
  }
}

5、util层

手动封装JDBCUtils工具类

package com.tjcu.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
 * @author 王恒杰
 * @version 1.0
 * @date 2021/9/11 12:38
 * @email 1078993387@qq.com
 * @Address 天津
 * @Description:
 */
public class JdbcUtils {
    //    静态的Properties集合,相当于属性
    private static Properties p = new Properties();
    //    静态的ThreadLocal输性  线程绑定对象
    private static final ThreadLocal<Connection> t = new ThreadLocal();
    static {
        InputStream is = JdbcUtils.class.getResourceAsStream("/com/tjcu/jdbc.properties");
        try {
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        //从ThreadLocal中获取Connection
        Connection conn = t.get();
        try {
            if (conn == null) {
                Class.forName(p.getProperty("driver"));
                conn = DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password"));
                t.set(conn);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t.get();
    }
    public static void close(ResultSet rs, PreparedStatement pstm, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pstm != null) {
            try {
                pstm.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
                t.remove();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static void close(ResultSet rs, PreparedStatement pstm) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pstm != null) {
            try {
                pstm.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static void close(PreparedStatement pstm, Connection conn) {
        if (pstm != null) {
            try {
                pstm.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
                //关闭链接后切记使用remove方法,移除ThreadLocal中已关闭的链接对象
                t.remove();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    //关闭资源  用于关闭连接
    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
                //关闭链接后切记使用remove方法,移除ThreadLocal中已关闭的链接对象
                t.remove();
            } catch (Exception e) {
            }
        }
    }
}

6、config 配置文件:jdbc.properties

mysql-connector-java-8.0.16.jar之后com.mysql.cj.jdbc.Driver

driver=com.mysql.cj.jdbc.Driver
username=root
password=root
url=jdbc:mysql://localhost:3306/msc?useUnicode=true&characterEncoding=UTF-8  & useSSL=false & serverTimezone=Asia/Shanghai

源代码在githee仓库:

程序员小王Gitee: https://gitee.com/wanghengjie563135/EMS.git


相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
8天前
|
存储 小程序 Java
热门小程序源码合集:微信抖音小程序源码支持PHP/Java/uni-app完整项目实践指南
小程序已成为企业获客与开发者创业的重要载体。本文详解PHP、Java、uni-app三大技术栈在电商、工具、服务类小程序中的源码应用,提供从开发到部署的全流程指南,并分享选型避坑与商业化落地策略,助力开发者高效构建稳定可扩展项目。
|
9天前
|
安全 Cloud Native Java
Java 模块化系统(JPMS)技术详解与实践指南
本文档全面介绍 Java 平台模块系统(JPMS)的核心概念、架构设计和实践应用。作为 Java 9 引入的最重要特性之一,JPMS 为 Java 应用程序提供了强大的模块化支持,解决了长期存在的 JAR 地狱问题,并改善了应用的安全性和可维护性。本文将深入探讨模块声明、模块路径、访问控制、服务绑定等核心机制,帮助开发者构建更加健壮和可维护的 Java 应用。
71 0
|
15天前
|
NoSQL Java 关系型数据库
超全 Java 学习路线,帮你系统掌握编程的超详细 Java 学习路线
本文为超全Java学习路线,涵盖基础语法、面向对象编程、数据结构与算法、多线程、JVM原理、主流框架(如Spring Boot)、数据库(MySQL、Redis)及项目实战等内容,助力从零基础到企业级开发高手的进阶之路。
103 2
|
1月前
|
Java 数据库 前端开发
分享44个java系统,总有一款适合您
分享44个微信小程序,总有一款适合您
37 0
|
1月前
|
消息中间件 Java Kafka
Java 事件驱动架构设计实战与 Kafka 生态系统组件实操全流程指南
本指南详解Java事件驱动架构与Kafka生态实操,涵盖环境搭建、事件模型定义、生产者与消费者实现、事件测试及高级特性,助你快速构建高可扩展分布式系统。
155 7
|
1月前
|
安全 Oracle Java
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
177 0
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
|
2月前
|
存储 Java 数据库连接
java 初学者必看的系统知识结构图详解
本文详解Java知识结构图,涵盖Java语言基础、JVM原理、集合框架、并发编程、网络通信及主流框架(如Spring Boot、MyBatis),并结合学生信息管理系统实例,帮助初学者构建完整知识体系,提升实战开发能力。
90 0
|
2月前
|
存储 Java 关系型数据库
Java Swing 开发的五星级酒店客房预订与管理系统源码
本文介绍了基于Java Swing的酒店管理系统开发方案。系统采用Java Swing构建GUI界面,结合MySQL数据库,实现预订管理、前台服务、客房管理、客户关系维护等功能模块。文章详细展示了登录界面、开房操作等核心功能的代码实现,包括数据验证和业务逻辑处理。该系统具有跨平台性,能有效提升酒店运营效率,为开发者提供GUI设计和数据库开发的实践案例。技术方案涵盖IntelliJ IDEA开发环境、Jform Designer插件辅助设计等工具链,适合中小型酒店管理需求。
139 0
|
3月前
|
NoSQL Java Shell
2025服务端java搭建篇:蜻蜓I即时通讯系统私有化部署深度指南-优雅草卓伊凡|麻子|贝贝
2025服务端java搭建篇:蜻蜓I即时通讯系统私有化部署深度指南-优雅草卓伊凡|麻子|贝贝
164 8
2025服务端java搭建篇:蜻蜓I即时通讯系统私有化部署深度指南-优雅草卓伊凡|麻子|贝贝
|
3月前
|
Java 调度 流计算
基于Java 17 + Spring Boot 3.2 + Flink 1.18的智慧实验室管理系统核心代码
这是一套基于Java 17、Spring Boot 3.2和Flink 1.18开发的智慧实验室管理系统核心代码。系统涵盖多协议设备接入(支持OPC UA、MQTT等12种工业协议)、实时异常检测(Flink流处理引擎实现设备状态监控)、强化学习调度(Q-Learning算法优化资源分配)、三维可视化(JavaFX与WebGL渲染实验室空间)、微服务架构(Spring Cloud构建分布式体系)及数据湖建设(Spark构建实验室数据仓库)。实际应用中,该系统显著提升了设备调度效率(响应时间从46分钟降至9秒)、设备利用率(从41%提升至89%),并大幅减少实验准备时间和维护成本。
255 0