Javaweb + MVC 实现企业人员管理系统全过程记录(配项目所有代码及数据库文件)
?
前言:因?yàn)檠芯可雽W(xué)任務(wù)需要做一個(gè)企業(yè)人員管理系統(tǒng),那就做唄。。。
項(xiàng)目及數(shù)據(jù)文件下載地址:https://download.csdn.net/download/qq_39410381/11546527
最終效果展示如下圖:
管理員登錄,界面如下:
?管理員輸入賬號和密碼,進(jìn)入主頁面,如下圖:
?管理員根據(jù)需求添加數(shù)據(jù),(這里以部門為例,點(diǎn)擊信息添加中部門添加),如下圖:
添加完信息后,管理員可查看所有數(shù)據(jù),(這里以部門為例),點(diǎn)擊信息展示中的部門展示,如下圖:
?管理員可根據(jù)需求在每條記錄右邊更改信息,更改狀態(tài)。
期間遇到的問題以及解決方案記錄如下:
報(bào)錯(cuò):HttpServlet cannot be resolved to a type?
解決:將tomcat包下的lib文件下的servlet-api.jar復(fù)制到WEB-INF下的lib文件夾中,即可解決
報(bào)錯(cuò):插入數(shù)據(jù)到數(shù)據(jù)庫中,中文會(huì)變?yōu)閱柼?br /> 解決:在數(shù)據(jù)庫連接配置時(shí),url后面加上 ?useUnicode=true&characterEncoding=UTF-8
報(bào)錯(cuò):javax.servlet.jsp.JspException cannot be resolved to a type
解決:在解決了第一個(gè)問題基礎(chǔ)上,再將tomcat包下的lib文件下的jsp-api.jar復(fù)制到WEB-INF下的lib文件夾中,即可解決
第一部分(項(xiàng)目設(shè)計(jì)&數(shù)據(jù)庫設(shè)計(jì)):
數(shù)據(jù)庫設(shè)計(jì):
管理員表:編號、賬號、密碼、狀態(tài)
部門表:編號、名稱、部門經(jīng)理、描述、狀態(tài)
職稱表:編號、名稱、基本工資、房補(bǔ)、職務(wù)補(bǔ)助、狀態(tài)
職工表:編號、姓名、性別、出生日期、籍貫、部門、職稱、狀態(tài)
項(xiàng)目設(shè)計(jì):非常簡單,就是管理員對職工進(jìn)行增刪改查,職工表有部門表和職稱表兩個(gè)外鍵
第二部分(環(huán)境搭建):
①下載jdk,我下的是java9,之后就是百度配置環(huán)境變量
②下載tomcat,這個(gè)最簡單,能啟動(dòng)就算成功
③下載ecplise,然后配置jdk和tomcat,有點(diǎn)復(fù)雜,耐心百度吧
④下載mysql數(shù)據(jù)庫和管理工具,我用的是5.7,管理工具是workbench
最終能通過ecplise啟動(dòng)一個(gè)頁面,打出hello world,環(huán)境就算成功了
第三部分(干活):
一、創(chuàng)建數(shù)據(jù)庫
數(shù)據(jù)庫名為?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;二、搭建項(xiàng)目
打開ecplise,右鍵->new->Dynamic Web Project,項(xiàng)目名為InformationManageProject
最終我的項(xiàng)目最終結(jié)構(gòu)如下圖:
?
找模板、改模板
由于目標(biāo)只是對后臺(tái)幾個(gè)表的增刪改查,所以找了一個(gè)后臺(tái)管理模板。
由于數(shù)據(jù)庫中沒有數(shù)據(jù),所有先改數(shù)據(jù)添加的模板,由于三個(gè)表添加類似,以部門表為例述說,如圖:
前端展示改好,修改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>三、實(shí)現(xiàn)邏輯(全部以部門表為例)
3.1 添加數(shù)據(jù)
因?yàn)閯倓?chuàng)建數(shù)據(jù)庫,什么數(shù)據(jù)都沒有,所以第一步就是添加數(shù)據(jù)。
修改前端的添加表單
<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>部門經(jīng)理</label><input type="text" name="manager" class="form-control" placeholder=" 請輸入該部門經(jīng)理"></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="#">同意遵守用戶協(xié)議</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)及其實(shí)現(xiàn)(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 展示數(shù)據(jù)
終于有了數(shù)據(jù),接下來,當(dāng)然是展示數(shù)據(jù)啦。
按照過程,第一個(gè)是主頁面的部門展示的url,后面帶了一個(gè)參數(shù),表示查詢?nèi)?/p> <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);//請求轉(zhuǎn)發(fā)跳轉(zhuǎn)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;}}好了,到現(xiàn)在為止,數(shù)據(jù)獲取到了,最后就是把它展示出來,所以修改部門展示頁面,這里不用前面,使用EL表達(dá)式,先導(dǎo)入了jstl的jar包,然后構(gòu)建路徑,最后在頁面頭部寫上?<%@ 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>經(jīng)理</th><th>描述</th><th>狀態(tài)</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 修改數(shù)據(jù)?
要想修改數(shù)據(jù),首先出現(xiàn)的問題就是回顯已有數(shù)據(jù),當(dāng)然在這之前,得在每個(gè)數(shù)據(jù)加上修改按鈕,如下:
?這里在每個(gè)鏈接上接上了對應(yīng)的id,依然使用的是EL表達(dá)式
<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>點(diǎn)擊修改后,跳轉(zhuǎn)到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調(diào)用Dao方法
?
最終,回顯數(shù)據(jù)成功,如下圖?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>部門經(jīng)理</label><input type="text" name="manager" class="form-control" placeholder=" 請輸入該部門經(jīng)理" 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">確認(rèn)修改</button> </form>然后傳達(dá)修改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調(diào)用底層Dao和實(shí)現(xiàn)
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;}}最后修改成功后,跳轉(zhuǎn)到展示所有的部門,至此修改結(jié)束。
3.4 刪除數(shù)據(jù)
最后一步,刪除數(shù)據(jù)相對更簡單了,因?yàn)槭羌賱h除,只是更改狀態(tài)就可以了,這里和同樣是更改狀態(tài)的“啟用”和“停用”一直說了。和前面一樣,前端代碼如下:
<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>?發(fā)送相應(yīng)的請求到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);}}} }由上面的代碼可以看出,它們公用了一個(gè)方法,改變部門的狀態(tài),其中:0:刪除;1:在用;2:停用
public interface DepartmentDao {...//修改部門狀態(tài)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;}}至此,關(guān)于部門的增刪改查操作全部結(jié)束,而對于職稱表和員工表都是一樣的,只是在員工表多了兩個(gè)外鍵,前端可使用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);//創(chuàng)建文本節(jié)點(diǎn)op.appendChild(node);root.appendChild(op);} });}getAllDepartments();</script>...而后端這邊主要是把數(shù)據(jù)轉(zhuǎn)換為json,這里我使用的方式是借助Gson.jar包實(shí)現(xiàn)轉(zhuǎn)換。
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轉(zhuǎn)換為jsonGson gson = new Gson(); String str = gson.toJson(depts);out.print(str);out.flush();out.close();} }最終效果圖如下:
?大致的內(nèi)容就是這么多,還有一些小的細(xì)節(jié),太瑣碎了,沒寫出來(比如防止在session放置管理員信息,每個(gè)頁面判斷一下是否按照正常登錄后進(jìn)入的,否則跳回到登錄頁面)。好了,暑假作業(yè)完成。
關(guān)于下載資源后如何啟動(dòng),我在我的windows系統(tǒng)上試了下,大致如下:
1.?數(shù)據(jù)庫:新建一個(gè)mysql數(shù)據(jù)庫,數(shù)據(jù)庫名為 citel_4 ,執(zhí)行database.sql文件
2. 導(dǎo)入項(xiàng)目:打開eclipse,File -> Import -> General -> Existing Projects into Workspace -> Browse -> 選擇InformationManageProject -> 選擇文件夾 -> Finish
NB. 注意修改數(shù)據(jù)庫連接配置信息: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. 啟動(dòng)項(xiàng)目:在Servers窗口中選中Tomcat v9.0 -> 點(diǎn)擊右邊綠色按鈕 (之后可在控制臺(tái)看見啟動(dòng)信息)
5. 在瀏覽器訪問項(xiàng)目:eg: http://localhost:8080/InformationManageProject/
總結(jié)
以上是生活随笔為你收集整理的Javaweb + MVC 实现企业人员管理系统全过程记录(配项目所有代码及数据库文件)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows cmd 进入其他盘
- 下一篇: 基于Java的建筑工程综合管理信息系统