Java SSM practice small project-take you to build a human resource management background system based on the SSM framework

Preface

I believe that after learning the three major architectures of SSM, many small partners don't know how to find a simple and easy-to-use project for practical training. They often see a good project on the blog and download it all in code, and there is nowhere to start. Therefore, this article strives to build a relatively complete backend system (that is, the entire process from login to logout) with the simplest and easy-to-understand project structure and code. (Suitable for novices)

The dynamic diagram of the operation process of the entire project is as follows (due to the limitation of CSDN on the size of uploaded pictures, the gif picture recorded here is very unclear, click on the picture to view it more clearly):
Write picture description here
(click on the picture to view)

The service has been deployed to the server and can be experienced online : link to online experience

The overall structure of the project:
Write picture description here
Write picture description here

The technology stacks used are:

  • Frame: SSM
  • Database: MySQL
  • Front-end framework: Bootstrap quickly build JSP pages
  • Project Management: MAVEN
  • Development tools: Intellij IDEA
  • Development environment: Windows

From this project, you can fully and independently experience the construction process from front-end to back-end, and use the SSM framework to complete the entire process of CRUD in the back-end.
Note: Project code download link: SSM_HRMS code download link .

1. Preparation

The preparation part mainly includes the establishment of the database table and the establishment of the SSM framework.
1 The database table
tbl_emp table:

DROP TABLE IF EXISTS `tbl_emp`;
CREATE TABLE `tbl_emp`(
	`emp_id` int(11) UNSIGNED NOT NULL auto_increment,
	`emp_name` VARCHAR(22) NOT NULL DEFAULT '',
  `emp_email` VARCHAR(256) NOT NULL DEFAULT '',
  `gender` CHAR(2) NOT NULL DEFAULT '',
   `department_id` int(11) NOT NULL DEFAULT 0,
	 PRIMARY KEY(`emp_id`)
) ENGINE=INNODB DEFAULT CHARSET=UTF8;

tbl_dept table:

DROP TABLE IF EXISTS `tbl_dept`;
CREATE TABLE `tbl_dept`(
	`dept_id` int(11) UNSIGNED NOT NULL auto_increment,
  `dept_name` VARCHAR(255) NOT NULL DEFAULT '',
	`dept_leader` VARCHAR(255) NOT NULL DEFAULT '',
	PRIMARY KEY(`dept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

For the corresponding entity classes, see bean/Employee.java and bean/Department.java.
(In the test part, run EmployeeMapperTest.java and DepartmentMapperTest.java, you can insert data into the table)

2 SSM project construction and startup
(1) This project uses MAVEN to manage the JAR package. First, import the dependent packages that may be used in the project:
see pom.xml.

(2) Web project configuration file: web.xml:
see WEB-INF/web.xml.

(3) Spring container configuration file: applicationContext.xml:
see resources/applicationContext.xml.

(4) SpringMVC configuration file: springmvc.xml:
see resources/springmvc.xml.

3 Test After
writing the above configuration files, you can create a new TestController.java file and WEB-INF/jsp/test.jsp in the controller directory to start the container to test whether it is successful.

2. DAO layer code completion and testing

This chapter mainly completes the implementation and testing of CRUD code at the bottom of the database.
1. MyBasits configuration file,
see resources/MyBatis.xml.

2. DAO layer code
First, write the relevant operation code of entity class Employee and table tbl_emp.
The main interfaces of EmployeeMapper.java are:

int deleteOneById(@Param("empId") Integer empId);
int updateOneById(@Param("empId") Integer empId,
                   @Param("employee") Employee employee);
int insertOne(Employee employee);           
 Employee selectOneById(@Param("empId") Integer empId);
Employee selectOneByName(@Param("empName") String empName);
// 查询带有部门信息的Employee
Employee selectWithDeptById(@Param("empId") Integer empId);
// 分页查询
List<Employee> selectByLimitAndOffset(@Param("limit") Integer limit,@Param("offset") Integer offset);
int countEmps();

For specific implementation, refer to the code in EmployeeMapper.java and EmployeeMapper.xml.

After writing, you need to test the implemented code to verify the correctness of the code.
For the test case code, see EmployeeMapperTest.java.

Similarly, the
implementation of the relevant operation code of the entity class Department and the table tbl_dept is similar to the above. For specific implementations, see DepartmentMapper.java and DepartmentMapper.xml, and for test case codes, see DepartmentMapperTest.java.

Third, the construction of the front-end page

The final effect of the front-end page is as follows.
main page:
Alt text

Employee operation page (similar to department operation page):
Write picture description here
(click on the picture to view)

Finally, add a landing page (the simpler page plus the simplest login judgment):
Write picture description here
(click on the picture to view)

The main thing is to use Bootstrap3 to build this front-end page, and then use the SSM framework + JSP to complete the entire process from front-end to back-end.
First of all, Bootstrap3 to build the front-end page.

1 Static construction of the main page

The HTML code implementation of the main page is placed in webapp/static/html/hrms_main.html (here only for easy viewing and reference).
After the entire main page is completed, extract the codes of the common parts, such as the navigation bar, the left sidebar, and the tail. These three parts belong to the public part.
See hrms_head.html, hrms_foot.html, and hrms_leftsidebar.html respectively. .

2 JSP implementation and layering of public pages

The HTML code of the above public part will be implemented with JSP below. For details, see head.jsp, foot.jsp, and leftsidebar.jsp in the WEB-INF/jsp/commom directory.

Then realize the content of the main page, which mainly includes three common parts (navigation bar + left side bar + tail + carousel part), the realization effect is as follows:
Write picture description here
(click on the picture to view)

Create a new main.jsp, import the codes of the above three public parts
<<%@ include file="./commom/xx.jsp"%>>, and then use Bootstrap to implement the carousel diagram part. For specific implementation, see the code in main.jsp.

3 Implementation of static pages for employee operations/department operations

The employee operation page has the same three common parts as the main page. The difference is that the middle part displays a table of employee information, while the main page is a carousel diagram.
Write picture description here
(Click on the picture to view)

The following will implement the employeePage page. For the detailed code, see employeePage.jsp (that is, the carousel part in main.jsp can be replaced with the employee form display part).

(In order to facilitate comparison and viewing, the implemented HTML part of the code is left in the project directory. For the
implemented HTML code, see WEB-INF/static/html/hrms_employee.html.
The pages displayed by the corresponding department are similar, and the
implemented HTML code is shown in WEB-INF/static/html/hrms_department.html.
Then the above codes are implemented with JSP pages respectively, that is, the corresponding employeePage.jsp and departmentPage.jsp.)

Four, front-end and back-end implementation of employee CRUD operations

1 Data display of employee information query

After the page is built, the data obtained from the background must be displayed on the corresponding page. The main realization of the page data display part is to use the JSP JSTL expression and AJAX+jQuery to display the data obtained from the background in the corresponding position of the page.

As the department operation is similar to the employee operation, the following mainly explains the realization of the employee display page.
The whole process is to query the data from the database, put it in the ModelAndView of SpringMVC, and then the front end can parse the obtained result set through JSTL.
(1) First write a JSON-related operation class: JsonMsg.java.
(2) Business operation: EmployeeService.java;
(3) Controller class: EmployeeController.java; The
interface ""emp/getEmpList?pageNo=XXX"" in EmployeeController.java returns the data corresponding to the number of pages according to the entered page number, and then use JSTL expressions are analyzed and displayed.

    @RequestMapping(value = "/getEmpList", method = RequestMethod.GET)
    public ModelAndView getEmp(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo){
        ModelAndView mv = new ModelAndView("");
        int limit = 5;
        // 记录的偏移量(即从第offset行记录开始查询),
        // 如第1页是从第1行(offset=(21-1)*5=0,offset+1=0+1=1)开始查询;
        // 第2页从第6行(offset=(2-1)*5=5,offset+1=5+1=6)记录开始查询
        int offset = (pageNo-1)*limit;
        //获取指定页数包含的员工信息
        List<Employee> employees = employeeService.getEmpList(offset, limit);
        //获取总的记录数
        int totalItems = employeeService.getEmpCount();
        //获取总的页数
        int temp = totalItems / limit;
        int totalPages = (totalItems % limit == 0) ? temp : temp+1;
        //当前页数
        int curPage = pageNo;

        //将上述查询结果放到Model中,在JSP页面中可以进行展示
        mv.addObject("employees", employees)
                .addObject("totalItems", totalItems)
                .addObject("totalPages", totalPages)
                .addObject("curPage", curPage);
        return mv;
    }

Then take out the data in the back-end Modal on the employeePage.jsp page for display.
The main codes are:

<tbody>
	<c:forEach items="${employees}" var="emp">
		 <tr>
		     <td>${emp.empId}</td>
		     <td>${emp.empName}</td>
		     <td>${emp.empEmail}</td>
		     <td>${emp.gender == "M"? "女": "男"}</td>
		     <td>${emp.department.deptName}</td>
		     <td>
		         <a href="#" role="button" class="btn btn-primary">编辑</a>
		         <a href="#" role="button" class="btn btn-danger">删除</a>
		      </td>
		</tr>
	</c:forEach>
</tbody>

with

<div class="table_items">
	当前第<span class="badge">${curPage}</span>页,共有<span class="badge">${totalPage}</span>页,总记录数<span class="badge">${totalItems}</span>条。
</div>

(4) The code implementation of the paging bar.
The finished effect of the pagination bar is as follows:
Write picture description here
(click on the picture to view)

The requirements that need to be completed for the pagination bar are:

  • The current page needs to be activated (mainly pages 1, 2, 3, 4, and 5 on the page);
  • On the homepage (page 1), << prohibit clicking;
  • On the last page (the last page), >> is forbidden to click;
  • Show homepage data by default;
  • First page, previous page, last page, next page add events, display corresponding page number data
  • Add a click event to each page of the middle page and jump to the corresponding page;
  • The current page X in the information bar on the left needs to be displayed synchronously according to the number of pages clicked.

The main code implementation is implemented using jQuery+JSTL on the front end. code show as below:

<div class="panel-body">
此处代码略
</div>

And the corresponding jQuery realizes the operation of the previous page and the next page:

$(function () {
        //上一页
        var curPage = ${curPage};
        var totalPages = ${totalPages};
        $(".prePage").click(function () {
            if (curPage > 1){
                var pageNo = curPage-1;
                $(this).attr("href", "/emp/getEmpList?pageNo="+pageNo);
            }
        });
        //下一页
        $(".nextPage").click(function () {
            if (curPage < totalPages){
                var pageNo = curPage+1;
                $(this).attr("href", "/emp/getEmpList?pageNo="+pageNo);
            }
        });
    })

Finally, add a designated link to the employee information in the main page to jump to the page where the current employee information is displayed (the department operation is similar, and will not be repeated), and when you click the company LOGO, you will jump to the main page.
The code is as follows:
head.jsp:

<script type="text/javascript">
    //跳转到主页面
    $("#company_logo").click(function () {
        $(this).attr("href", "/hrms/main");
    });

leftsidebar.jsp:

<script type="text/javascript">
    //跳转到员工页面
    $(".emp_info").click(function () {
        $(this).attr("href", "/hrms/emp/getEmpList");
    });
    //跳转到部门页面
    $(".dept_info").click(function () {
        $(this).attr("href", "/hrms/dept/getDeptList");
    });
</script>

At this point, the display part of the employee information is basically completed.

2 Staff addition

Next, new operations of employees will be implemented, as well as simple verification of newly added data.
The finished page effect is as follows:
Write picture description here
(click on the picture to view)

The main requirements are:

  • (1) Click the employee add button in the left column, and the modal page for employee addition will pop up;
  • (2) Verify the entered name and email format, if the format is incorrect, an error message will be prompted;
  • (4) Judge whether the entered name is repeated or not, and if it is repeated, it will prompt repeated information;
  • (5) After successful addition, jump to the page where the added record is located (the last page);
  • (6) If adding fails, an error message will be displayed.

The background code implementation mainly includes:

    /**
     * 查询输入的员工姓名是否重复
     * @param empName
     * @return
     */
    @RequestMapping(value = "/checkEmpExists", method = RequestMethod.GET)
    @ResponseBody
    public JsonMsg checkEmpExists(@RequestParam("empName") String empName){
        //对输入的姓名与邮箱格式进行验证
        String regName = "(^[a-zA-Z0-9_-]{3,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
        if(!empName.matches(regName)){
            return JsonMsg.fail().addInfo("name_reg_error", "输入姓名为2-5位中文或6-16位英文和数字组合");
        }
        Employee employee = employeeService.getEmpByName(empName);
        if (employee != null){
            return JsonMsg.fail().addInfo("name_reg_error", "用户名重复");
        }else {
            return JsonMsg.success();
        }
    }

    /**
     * 新增记录后,查询最新的页数
     * @return
     */
    @RequestMapping(value = "/getTotalPages", method = RequestMethod.GET)
    @ResponseBody
    public JsonMsg getTotalPage(){
        int totalItems = employeeService.getEmpCount();
        //获取总的页数
        int temp = totalItems / 5;
        int totalPages = (totalItems % 5 == 0) ? temp : temp+1;
        return JsonMsg.success().addInfo("totalPages", totalPages);
    }

    /**
     * 新增员工
     * @param employee 新增的员工信息
     * @return
     */
    @RequestMapping(value = "/addEmp", method = RequestMethod.POST)
    @ResponseBody
    public JsonMsg addEmp(Employee employee){
        int res = employeeService.addEmp(employee);
        if (res == 1){
            return JsonMsg.success();
        }else {
            return JsonMsg.fail();
        }
    }

For the front-end code, see employeeAdd.jsp.
Mainly jQuey operations, many operations can be encapsulated into a function to call, such as the display of error messages. This article is not encapsulated for ease of viewing.

3 Staff changes

The completion page of the staff modification operation is as follows:
Write picture description here
Write picture description here
(click on the picture to view)

The main requirements for the changes are:

  • (1) Obtain and click to modify the id and name of the employee;
  • (2) Query the corresponding employee information according to id or name, and then display it back;
  • (3) Echo the list of departments;
  • (4) Make modifications and judge the modified mailbox format;
  • (5) Click the update button to send an AJAX request to the background for saving;
  • (6) After the change is successful, jump to the current change page.

The background code implementation mainly includes:

    /**
     * 更改员工信息
     * @param empId
     * @param employee
     * @return
     */
    @RequestMapping(value ="/updateEmp/{empId}", method = RequestMethod.PUT)
    @ResponseBody
    public JsonMsg updateEmp(@PathVariable("empId") Integer empId,  Employee employee){
        int res = employeeService.updateEmpById(empId, employee);
        if (res != 1){
            return JsonMsg.fail().addInfo("emp_update_error", "更改异常");
        }
        return JsonMsg.success();
    }

For the front-end page + jQuery code, see: employeeUpdate.jsp .

4 Employee delete

The employee delete operation complete page is as follows:
Write picture description here
(click on the picture to view)

The main requirements for deletion are:

  • (1) A confirmation box pops up: whether to delete XX information;
  • (2) Send an AJAX request to perform the delete operation;
  • (3) After the deletion is successful, jump to the current page.

Background code:

    /**
     * 员工删除操作
     * @param empId
     * @return
     */
    @RequestMapping(value = "/deleteEmp/{empId}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonMsg deleteEmp(@PathVariable("empId") Integer empId){
        int res = employeeService.deleteEmpById(empId);
        if (res != 1){
            return JsonMsg.fail().addInfo("emp_del_error", "员工删除异常");
        }
        return JsonMsg.success();
    }

For the front-end page code, see employeePage.jsp:

    <!-- ==========================员工删除操作=================================== -->
    $(".emp_delete_btn").click(function () {
        var curPage = ${curPage};
        var delEmpId = $(this).parent().parent().find("td:eq(0)").text();
        var delEmpName = $(this).parent().parent().find("td:eq(1)").text();
        if (confirm("确认删除【" + delEmpName+ "】的信息吗?")){
            $.ajax({
                url:"/hrms/emp/deleteEmp/"+delEmpId,
                type:"DELETE",
                success:function (result) {
                    if (result.code == 100){
                        alert("删除成功!");
                        window.location.href="/hrms/emp/getEmpList?pageNo="+curPage;
                    }else {
                        alert(result.extendInfo.emp_del_error);
                    }
                }
            });
        }
    });

At this point, the addition, deletion, modification, and checking operations of the SSM project have basically been completed. The department operations are similar to the above. This article will not repeat them. If you are interested, you can skim the code of the Department related operations.

5 Login page

Finally, for the completeness of the project, a landing page is added, and the achieved effect is
as follows:
Write picture description here
(click on the picture to view)

A simple login verification is mainly done in the background, and the code can be seen in LoginController.java:

    /**
     * 登录:跳转到登录页面
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    /**
     * 对登录页面输入的用户名和密码做简单的判断
     * @param request
     * @return
     */
    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    @ResponseBody
    public JsonMsg dologin(HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username + password);
        if (!"admin1234".equals(username + password)){
            return JsonMsg.fail().addInfo("login_error", "输入账号用户名与密码不匹配,请重新输入!");
        }
        return JsonMsg.success();
    }

    /**
     * 跳转到主页面
     * @return
     */
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String main(){
        return "main";
    }

    /**
     * 退出登录:从主页面跳转到登录页面
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(){
        return "login";
    }

For the front page, please refer to the login.jsp code; and for the operation of the logout button, please refer to head.jsp:

//账号退出
$(".hrms_logout").click(function () {
  window.location.href = "/hrms/logout";
});

Note:
Container placement:
Insert picture description here

Five, project code download

Finally, upload the code of this project to my github. If you want to download the source code of the project: Click here .
If you think it's helpful, don't forget to order a star on my github, THX!

If any problem, contact me with QQ: 1032335358. (please specify from CSDN)

2018/03/09 in NJ.


【Page 404 fix】-fix in 2019/01/31

This time is relatively busy, and many students’ comments have not had time to reply, so I’m very sorry.
After reading the comments, it is basically the problem of no response to login and 404 when clicking on the page. 404 is generally an absolute path problem. You can add an absolute path to the code and there will be no error.
When configuring the container, just click on the following configuration to solve the above problems.
Insert picture description here

Guess you like

Origin blog.csdn.net/noaman_wgs/article/details/79503559