Javaweb + MVC 实现企业人员管理系统全过程记录(配项目所有代码及数据库文件)
?
前言:因為研究生入學任務需要做一個企業人員管理系統,那就做唄。。。
項目及數據文件下載地址:https://download.csdn.net/download/qq_39410381/11546527
最終效果展示如下圖:
管理員登錄,界面如下:
?管理員輸入賬號和密碼,進入主頁面,如下圖:
?管理員根據需求添加數據,(這里以部門為例,點擊信息添加中部門添加),如下圖:
添加完信息后,管理員可查看所有數據,(這里以部門為例),點擊信息展示中的部門展示,如下圖:
?管理員可根據需求在每條記錄右邊更改信息,更改狀態。
期間遇到的問題以及解決方案記錄如下:
報錯:HttpServlet cannot be resolved to a type?
解決:將tomcat包下的lib文件下的servlet-api.jar復制到WEB-INF下的lib文件夾中,即可解決
報錯:插入數據到數據庫中,中文會變為問號
解決:在數據庫連接配置時,url后面加上 ?useUnicode=true&characterEncoding=UTF-8
報錯:javax.servlet.jsp.JspException cannot be resolved to a type
解決:在解決了第一個問題基礎上,再將tomcat包下的lib文件下的jsp-api.jar復制到WEB-INF下的lib文件夾中,即可解決
第一部分(項目設計&數據庫設計):
數據庫設計:
管理員表:編號、賬號、密碼、狀態
部門表:編號、名稱、部門經理、描述、狀態
職稱表:編號、名稱、基本工資、房補、職務補助、狀態
職工表:編號、姓名、性別、出生日期、籍貫、部門、職稱、狀態
項目設計:非常簡單,就是管理員對職工進行增刪改查,職工表有部門表和職稱表兩個外鍵
第二部分(環境搭建):
①下載jdk,我下的是java9,之后就是百度配置環境變量
②下載tomcat,這個最簡單,能啟動就算成功
③下載ecplise,然后配置jdk和tomcat,有點復雜,耐心百度吧
④下載mysql數據庫和管理工具,我用的是5.7,管理工具是workbench
最終能通過ecplise啟動一個頁面,打出hello world,環境就算成功了
第三部分(干活):
一、創建數據庫
數據庫名為?citel_4
建表
CREATE TABLE `citel_4`.`admins` (`id` INT NOT NULL AUTO_INCREMENT,`account` VARCHAR(45) NULL,`password` VARCHAR(45) NULL,`status` INT NULL,PRIMARY KEY (`id`)); CREATE TABLE `citel_4`.`departments` (`id` INT NOT NULL AUTO_INCREMENT,`name` VARCHAR(45) NULL,`manager` VARCHAR(45) NULL,`description` VARCHAR(45) NULL,`status` INT NULL,PRIMARY KEY (`id`)); CREATE TABLE `citel_4`.`titles` (`id` INT NOT NULL AUTO_INCREMENT,`name` VARCHAR(45) NULL,`base_wage` VARCHAR(45) NULL,`room_supply` VARCHAR(45) NULL,`job_supply` VARCHAR(45) NULL,`status` INT NULL,PRIMARY KEY (`id`)); CREATE TABLE `citel_4`.`staffs` (`id` INT NOT NULL AUTO_INCREMENT,`name` VARCHAR(45) NULL,`sex` CHAR(1) NULL,`birth` VARCHAR(45) NULL,`home` VARCHAR(45) NULL,`department` INT NULL,`title` INT NULL,`status` INT NULL,PRIMARY KEY (`id`));?添加外鍵
ALTER TABLE `citel_4`.`staffs` ADD INDEX `fk_department_idx` (`department` ASC); ; ALTER TABLE `citel_4`.`staffs` ADD CONSTRAINT `fk_department`FOREIGN KEY (`department`)REFERENCES `citel_4`.`departments` (`id`)ON DELETE CASCADEON UPDATE CASCADE;ALTER TABLE `citel_4`.`staffs` ADD INDEX `fk_title_idx` (`title` ASC); ; ALTER TABLE `citel_4`.`staffs` ADD CONSTRAINT `fk_title`FOREIGN KEY (`title`)REFERENCES `citel_4`.`titles` (`id`)ON DELETE CASCADEON UPDATE CASCADE;二、搭建項目
打開ecplise,右鍵->new->Dynamic Web Project,項目名為InformationManageProject
最終我的項目最終結構如下圖:
?
找模板、改模板
由于目標只是對后臺幾個表的增刪改查,所以找了一個后臺管理模板。
由于數據庫中沒有數據,所有先改數據添加的模板,由于三個表添加類似,以部門表為例述說,如圖:
前端展示改好,修改web.xml
<servlet><servlet-name>DepartmentServlet</servlet-name><servlet-class>com.sky.servlets.DepartmentServlet</servlet-class></servlet><servlet-mapping><servlet-name>DepartmentServlet</servlet-name><url-pattern>*.department</url-pattern></servlet-mapping>三、實現邏輯(全部以部門表為例)
3.1 添加數據
因為剛創建數據庫,什么數據都沒有,所以第一步就是添加數據。
修改前端的添加表單
<form action="<%=request.getContextPath() %>/add.department" method="post"><input type="hidden" name="operation" value="add"><div class="form-group"><label>部門名稱</label><input type="text" name="name" class="form-control" placeholder="請輸入部門名稱"></div><div class="form-group"><label>部門經理</label><input type="text" name="manager" class="form-control" placeholder=" 請輸入該部門經理"></div><div class="form-group"><label>部門描述</label><input type="text" name="description" class="form-control" placeholder="請描述該部門"></div><div class="checkbox"><label><input type="checkbox"> <a href="#">同意遵守用戶協議</a> </label></div><button type="submit" class="btn btn-primary btn-flat m-b-30 m-t-30">添加</button> </form>后端?DepartmentServlet
public class DepartmentServlet extends HttpServlet {private static final long serialVersionUID = 1L;DepartmentDao departmentDao = new DepartmentDaoImpl();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("utf-8");String operation = req.getParameter("operation");if (operation.equals("query")) {//testint id = Integer.parseInt(req.getParameter("id"));Departments dept = departmentDao.selectOneById(id);System.out.println("data: " + dept);}else if (operation.equals("add")) {String name = req.getParameter("name");String manager = req.getParameter("manager");String description = req.getParameter("description");boolean res = departmentDao.addOneDepartment(new Departments(name, manager, description));if (res) {//添加成功req.getRequestDispatcher("/index.jsp").forward(req, resp);} else {//添加失敗req.getRequestDispatcher("/error.jsp").forward(req, resp);}}} }之后是Dao層(DepartmentDao)及其實現(DepartmentDaoImpl)
public interface DepartmentDao {//按ID查詢部門Departments selectOneById(Integer id);//添加部門boolean addOneDepartment(Departments dept); } public class DepartmentDaoImpl implements DepartmentDao{Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;Boolean result = false;Departments dept = null;@Overridepublic Departments selectOneById(Integer id) {try {conn = DBUtils.getConnection();ps = conn.prepareStatement("SELECT * FROM citel_4.departments where id = ?;");ps.setInt(1, id);rs = ps.executeQuery();if(rs.next()){int _id = rs.getInt(1);String _name = rs.getString(2);String _manager = rs.getString(3);String _description = rs.getString(4);int _status = rs.getInt(5);dept = new Departments(_id, _name, _manager, _description, _status);}} catch (Exception e) {e.printStackTrace();}finally{DBUtils.closeAll(rs, ps, conn);}return dept;}@Overridepublic boolean addOneDepartment(Departments dept) {try {conn = DBUtils.getConnection();ps = conn.prepareStatement("insert into departments values (0, ?, ?, ?, 1);");ps.setString(1, dept.getName());ps.setString(2, dept.getManager());ps.setString(3, dept.getDescription());result = ps.executeUpdate()>0?true:false;} catch (Exception e) {e.printStackTrace();}finally{DBUtils.closeAll(rs, ps, conn);}return result;}}最終添加部門效果:
3.2 展示數據
終于有了數據,接下來,當然是展示數據啦。
按照過程,第一個是主頁面的部門展示的url,后面帶了一個參數,表示查詢全部
<li><a class="sidebar-sub-toggle"><i class="ti-layout-grid4-alt"></i> 信息展示 <span class="sidebar-collapse-icon ti-angle-down"></span></a><ul><li><a href="<%=request.getContextPath() %>/queryAll.department?operation=queryAll">部門展示</a></li><li><a href="table-basic.html">職位展示</a></li><li><a href="table-basic.html">員工展示</a></li></ul> </li>?接下來,處理servlet
public class DepartmentServlet extends HttpServlet {private static final long serialVersionUID = 1L;DepartmentDao departmentDao = new DepartmentDaoImpl();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {...//省略,前面寫過,后面代碼一樣}else if (operation.equals("queryAll")) {List<Departments> depts = departmentDao.selectAllDepartments();req.setAttribute("departments", depts);//請求轉發跳轉req.getRequestDispatcher("/show-department.jsp").forward(req, resp);}} }?然后是Dao層代碼邏輯
public interface DepartmentDao {...//查詢所有部門List<Departments> selectAllDepartments(); }?
public class DepartmentDaoImpl implements DepartmentDao{Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;Boolean result = false;Departments dept = null;List<Departments> list = null;... @Overridepublic List<Departments> selectAllDepartments() {try {conn = DBUtils.getConnection();ps = conn.prepareStatement("SELECT * FROM departments where status=1 or status=2;");rs = ps.executeQuery();list = new ArrayList<Departments>();while (rs.next()) {int id = rs.getInt(1);String name = rs.getString(2);String manager = rs.getString(3);String description = rs.getString(4);int status = rs.getInt(5);Departments dept = new Departments(id, name, manager, description, status);list.add(dept);}} catch (Exception e) {e.printStackTrace();}finally{DBUtils.closeAll(rs, ps, conn);}return list;}}好了,到現在為止,數據獲取到了,最后就是把它展示出來,所以修改部門展示頁面,這里不用前面,使用EL表達式,先導入了jstl的jar包,然后構建路徑,最后在頁面頭部寫上?<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 就可以了。展示頁面代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@page import="java.util.List"%> <%@page import="com.sky.pojo.Departments"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html lang="en">...<table class="table table-hover "><thead><tr><th>#</th><th>名稱</th><th>經理</th><th>描述</th><th>狀態</th><th>操作</th></tr></thead><tbody><c:forEach items="${departments}" var="department"><tr> <td scope="row">${department.id}</td> <td>${department.name}</td> <td>${department.manager}</td> <td>${department.description}</td><c:if test="${department.status eq '1' }"><td><span class="badge badge-success">在用</span></td><td>停用</td></c:if><c:if test="${department.status eq '2' }"><td><span class="badge badge-danger">停用</span></td><td>啟用</td></c:if></tr></c:forEach></tbody> </table>...?
最終效果圖:
3.3 修改數據?
要想修改數據,首先出現的問題就是回顯已有數據,當然在這之前,得在每個數據加上修改按鈕,如下:
?這里在每個鏈接上接上了對應的id,依然使用的是EL表達式
<c:if test="${department.status eq '1' }"><td><span class="badge badge-success">在用</span></td><td><a href="${pageContext.request.contextPath}/download.department?operation=download&id=${department.id}">停用</a>/<a href="${pageContext.request.contextPath}/update.department?operation=showOne&id=${department.id}">修改</a>/<a href=" ${pageContext.request.contextPath}/delete.department?operation=delete&id=${department.id}">刪除</a></td> </c:if> <c:if test="${department.status eq '2' }"><td><span class="badge badge-danger">停用</span></td><td><a href="${pageContext.request.contextPath}/upload.department?operation=upload&id=${department.id}">啟用</a>/<a href="${pageContext.request.contextPath}/showOne.department?operation=showOne&id=${department.id}">修改</a>/<a href="${pageContext.request.contextPath}/delete.department?operation=delete&id=${department.id}">刪除</a></td> </c:if>點擊修改后,跳轉到servlet,
public class DepartmentServlet extends HttpServlet {...@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("utf-8");String operation = req.getParameter("operation");if (operation.equals("showOne")) {int id = Integer.parseInt(req.getParameter("id"));Departments dept = departmentDao.selectOneById(id);req.setAttribute("department", dept);req.getRequestDispatcher("/update-department.jsp").forward(req, resp);}... } }servlet調用Dao方法
?
最終,回顯數據成功,如下圖?update-department.jsp
?該頁面的表單改寫如下:
<form action="<%=request.getContextPath() %>/update.department" method="post"><input type="hidden" name="operation" value="update"><input type="hidden" name="id" value="${department.id}"><input type="hidden" name="status" value="${department.status}"><div class="form-group"><label>部門名稱</label><input type="text" name="name" class="form-control" placeholder="請輸入部門名稱" value="${department.name }"></div><div class="form-group"><label>部門經理</label><input type="text" name="manager" class="form-control" placeholder=" 請輸入該部門經理" value="${department.manager }"></div><div class="form-group"><label>部門描述</label><input type="text" name="description" class="form-control" placeholder="請描述該部門" value="${department.description }"></div><button type="submit" class="btn btn-primary btn-flat m-b-30 m-t-30">確認修改</button> </form>然后傳達修改servlet,
public class DepartmentServlet extends HttpServlet {...@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {...}else if (operation.equals("update")) { //修改int id = Integer.parseInt(req.getParameter("id"));String name = req.getParameter("name");String manager = req.getParameter("manager");String description = req.getParameter("description");int status = Integer.parseInt(req.getParameter("status"));Departments dept = new Departments(id, name, manager, description, status);res = departmentDao.updateDepartment(dept);if (res) {//修改成功resp.sendRedirect(req.getContextPath()+"/queryAll.department?operation=queryAll");} else {//修改失敗req.getRequestDispatcher("/error.jsp").forward(req, resp);}}} }servlet調用底層Dao和實現
public interface DepartmentDao {...//修改部門信息boolean updateDepartment(Departments newDeptDepartments); } public class DepartmentDaoImpl implements DepartmentDao{...@Overridepublic boolean updateDepartment(Departments newDeptDepartments) {try {conn = DBUtils.getConnection();ps = conn.prepareStatement("update citel_4.departments set name=?, manager=?, description=?,status=? where id=?;");ps.setString(1, newDeptDepartments.getName());ps.setString(2, newDeptDepartments.getManager());ps.setString(3, newDeptDepartments.getDescription());ps.setInt(4, newDeptDepartments.getStatus());ps.setInt(5, newDeptDepartments.getId());result = ps.executeUpdate()>0?true:false;} catch (Exception e) {e.printStackTrace();}finally{DBUtils.closeAll(rs, ps, conn);}return result;}}最后修改成功后,跳轉到展示所有的部門,至此修改結束。
3.4 刪除數據
最后一步,刪除數據相對更簡單了,因為是假刪除,只是更改狀態就可以了,這里和同樣是更改狀態的“啟用”和“停用”一直說了。和前面一樣,前端代碼如下:
<c:if test="${department.status eq '1' }"><td><span class="badge badge-success">在用</span></td><td><a href="${pageContext.request.contextPath}/download.department?operation=download&id=${department.id}">停用</a>/<a href="${pageContext.request.contextPath}/update.department?operation=showOne&id=${department.id}">修改</a>/<a href=" ${pageContext.request.contextPath}/delete.department?operation=delete&id=${department.id}">刪除</a></td> </c:if> <c:if test="${department.status eq '2' }"><td><span class="badge badge-danger">停用</span></td><td><a href="${pageContext.request.contextPath}/upload.department?operation=upload&id=${department.id}">啟用</a>/<a href="${pageContext.request.contextPath}/showOne.department?operation=showOne&id=${department.id}">修改</a>/<a href="${pageContext.request.contextPath}/delete.department?operation=delete&id=${department.id}">刪除</a></td> </c:if>?發送相應的請求到servlet,代碼如下:
public class DepartmentServlet extends HttpServlet {...@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {...}else if (operation.equals("upload")) { //啟用int id = Integer.parseInt(req.getParameter("id"));res = departmentDao.updatedepartmentStatus(id, 1);if (res) {resp.sendRedirect(req.getContextPath()+"/queryAll.department?operation=queryAll");} else {req.getRequestDispatcher("/error.jsp").forward(req, resp);}}else if (operation.equals("download")) { //停用int id = Integer.parseInt(req.getParameter("id"));res = departmentDao.updatedepartmentStatus(id, 2);if (res) {resp.sendRedirect(req.getContextPath()+"/queryAll.department?operation=queryAll");} else {req.getRequestDispatcher("/error.jsp").forward(req, resp);}}else if (operation.equals("delete")) { //刪除int id = Integer.parseInt(req.getParameter("id"));res = departmentDao.updatedepartmentStatus(id, 0);if (res) {resp.sendRedirect(req.getContextPath()+"/queryAll.department?operation=queryAll");} else {req.getRequestDispatcher("/error.jsp").forward(req, resp);}}} }由上面的代碼可以看出,它們公用了一個方法,改變部門的狀態,其中:0:刪除;1:在用;2:停用
public interface DepartmentDao {...//修改部門狀態boolean updatedepartmentStatus(Integer id,Integer status);} public class DepartmentDaoImpl implements DepartmentDao{...@Overridepublic boolean updatedepartmentStatus(Integer id,Integer status) {try {conn = DBUtils.getConnection();ps = conn.prepareStatement("update departments set status=? where id=?;");ps.setInt(1, status);ps.setInt(2, id);result = ps.executeUpdate()>0?true:false;} catch (Exception e) {e.printStackTrace();}finally{DBUtils.closeAll(rs, ps, conn);}return result;}}至此,關于部門的增刪改查操作全部結束,而對于職稱表和員工表都是一樣的,只是在員工表多了兩個外鍵,前端可使用axios,先去獲取所有的部門和職稱,然后讓用戶選擇即可。
...<script src="//cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script><script type="text/javascript">function getAllDepartments(){axios.get("InformationManageProject/queryAll.department?operation=queryAllByAjax").then((response)=> {dataList = response.data;//console.log(dataList);var root = document.getElementById('depts');for(var i=0;i<dataList.length;i++){var op = document.createElement("option");op.setAttribute("value", dataList[i].id);var node=document.createTextNode(dataList[i].name);//創建文本節點op.appendChild(node);root.appendChild(op);} });}getAllDepartments();</script>...而后端這邊主要是把數據轉換為json,這里我使用的方式是借助Gson.jar包實現轉換。
else if (operation.equals("queryAllByAjax")) {resp.setContentType("application/json; charset=utf-8"); req.setCharacterEncoding("UTF-8");PrintWriter out = resp.getWriter();List<Departments> depts = departmentDao.selectAllDepartments();//list轉換為jsonGson gson = new Gson(); String str = gson.toJson(depts);out.print(str);out.flush();out.close();} }最終效果圖如下:
?大致的內容就是這么多,還有一些小的細節,太瑣碎了,沒寫出來(比如防止在session放置管理員信息,每個頁面判斷一下是否按照正常登錄后進入的,否則跳回到登錄頁面)。好了,暑假作業完成。
關于下載資源后如何啟動,我在我的windows系統上試了下,大致如下:
1.?數據庫:新建一個mysql數據庫,數據庫名為 citel_4 ,執行database.sql文件
2. 導入項目:打開eclipse,File -> Import -> General -> Existing Projects into Workspace -> Browse -> 選擇InformationManageProject -> 選擇文件夾 -> Finish
NB. 注意修改數據庫連接配置信息:db-config.properties
3.1 綁定Tomcat:Window -> Preference -> Server -> Runtime Environments -> Add -> 選擇Apache Tomcat v9.0 -> Apply and Close
3.2 打開Servers窗口:Window -> Show View -> Servers
3.3?在Servers窗口中:右鍵 -> Add and Remove -> 選擇選擇InformationManageProject -> Add -> Finish
4. 啟動項目:在Servers窗口中選中Tomcat v9.0 -> 點擊右邊綠色按鈕 (之后可在控制臺看見啟動信息)
5. 在瀏覽器訪問項目:eg: http://localhost:8080/InformationManageProject/
總結
以上是生活随笔為你收集整理的Javaweb + MVC 实现企业人员管理系统全过程记录(配项目所有代码及数据库文件)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows cmd 进入其他盘
- 下一篇: 【openjudge 计算概论(A)】[