小型员工管理系统 1.0 绿色版(java实现版)
员工管理系统简介:
整个系统其实很简单,这里主要技术:idea开发工具+JSP + Struts2+ JDBC + Mysql实现 1、管理员的登录,注册,验证码功能 2、员工的增删改查,批量删除,上传文件,下载文件 其中类的设计(实体)很有参考意义。 整个系统设计的目标人群是管理者,系统的主要功能是对员工进行各种信息的操作。 主要是完成对数据库的增删改查的功能。
一. 项目整体目录结构
MVC实现,界面层(Web)主要使用jsp来动态展现数据库中的数据,业务逻辑层(servlets)使用的servlet,数据访问层(dao)主要是连接各个Servlet与数据库之前的通信,从而实现对数据库的各种操作。其中的entity包主要是封装了两个实体:管理员和员工,方便且规范对数据的操作和代码的书写。
二. 界面效果展示:
1、管理员页面
(1)管理员登录页面
(2)管理员注册页面
2、员工页面
(1)员工页面展示
页面展示完成员工的增删改查,员工资料管理系统:完成上传文件,下载文件
(2)员工更新【页面数据回显】
(3)添加员工页面
三、数据库设计
1、admin表(管理员的账号和密码)
2、user表(员工信息表)
四、核心jar包(jar包下载参见文章末尾)
五、核心代码展示:(完整代码参见文章末尾)
1、entity类
(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层
(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层[略,详情请参见文章末尾]
4、struts2实现Action层
(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