原作者Github:https://github.com/GenshenWang/SSM_HRMS
配置文件
db.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/zl?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC jdbc.username=root jdbc.password=1870535196
Log4j.properties
# Configure logging for testing: optionally with log file log4j.rootLogger=WARN, stdout # log4j.rootLogger=WARN, stdout, logfile log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.File=target/spring.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
MybatisConfig.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> </beans>
<!-- 配置数据库相关参数properties属性--> <context:property-placeholder location="classpath:db.properties"/>
<!-- 数据库连接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置连接池属性--> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- c3p0连接池的私有属性 --> <property name="maxPoolSize" value="30" /> <property name="minPoolSize" value="10" /> <!-- 关闭连接后不自动commit --> <property name="autoCommitOnClose" value="false" /> <!-- 获取连接超时时间 --> <property name="checkoutTimeout" value="10000" /> <!-- 当获取连接失败重试次数 --> <property name="acquireRetryAttempts" value="2" /> </bean>
<!-- SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池--> <property name="dataSource" ref="dataSource"/> <!-- 别名--> <property name="typeAliasesPackage" value="cn.imut.pojo"/> <!-- 扫描xml--> <property name="mapperLocations" value="classpath:Dao/*.xml"/> </bean>
<!-- 配置一个可以执行批量的sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/> <constructor-arg name="executorType" value="BATCH"/> </bean>
<!-- 配置扫描dao--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.imut.dao"/> </bean>
<!-- 配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!-- 配置AOP--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.imut.service.impl.*ServiceImpl.*(..))"/> </aop:config>
springmvc.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> </beans>
<!-- 配置视图解析器--> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
<!-- 处理静态资源--> <mvc:default-servlet-handler/>
<!-- 开启注解--> <mvc:annotation-driven/>
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> </beans>
<context:component-scan base-package="cn.imut"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
<import resource="MybatisConfig.xml"/>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> </web-app>
<!-- 启动页面 --> <welcome-file-list> <welcome-file>/WEB-INF/jsp/main.jsp</welcome-file> </welcome-file-list>
<!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<!--启动Spring容器--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
<!-- SpringMVC前端(视图)控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 加载springmvc.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 启动服务器,创建servlet--> <load-on-startup>1</load-on-startup> </servlet>
<!-- 拦截所有请求--> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
<!-- springMVC自带过滤器--> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<!-- 4、使用Rest风格的URI,将页面普通的post请求转为指定的delete或者put请求 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<!--HttpPutFormContentFilter:将请求体中的数据解析包装成一个map --> <filter> <filter-name>HttpPutFormContentFilter</filter-name> <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class> </filter> <filter-mapping> <filter-name>HttpPutFormContentFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
EmployeeDao.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="cn.imut.dao.EmployeeDao"> <resultMap id="withDeptResultMap" type="cn.imut.pojo.Employee"> <id column="emp_id" property="empId"/> <result column="emp_name" property="empName"/> <result column="emp_email" property="empEmail"/> <result column="gender" property="gender"/> <result column="department_id" property="departmentId"/> <association property="department" column="department_id" javaType="cn.imut.pojo.Department"> <id column="dept_id" property="deptId"/> <result column="dept_leader" property="deptLeader"/> <result column="dept_name" property="deptName"/> </association> </resultMap> <select id="selectWithDeptById" parameterType="Integer" resultMap="withDeptResultMap"> SELECT emp_id, emp_name, emp_email, gender, department_id, dept_id, dept_leader, dept_name FROM tbl_emp e, tbl_dept d WHERE e.department_id = d.dept_id AND e.emp_id = #{empId} </select> <select id="selectByLimitAndOffset" resultMap="withDeptResultMap"> SELECT emp_id, emp_name, emp_email, gender, department_id, dept_id, dept_leader, dept_name FROM tbl_emp e LEFT JOIN tbl_dept d ON e.department_id = d.dept_id ORDER BY e.emp_id LIMIT #{offset}, #{limit} </select> </mapper>
pojo层
Department.java
//部门实体类 @Data @NoArgsConstructor @AllArgsConstructor public class Department { private Integer deptId; //部门号 private String deptLeader; //部长姓名 private String deptName; //部门名字 }
Employee.java
//员工实体类 @Data @NoArgsConstructor @AllArgsConstructor public class Employee { private Integer empId; //员工号 private String empName; //员工姓名 private String empEmail; //邮箱 private String gender; //性别 private Integer departmentId; //部门号 private Department department; //部门实体类 public Employee(Integer empId, String empName, String empEmail, String gender, Integer departmentId) { this.empId = empId; this.empName = empName; this.empEmail = empEmail; this.gender = gender; this.departmentId = departmentId; } }
Dao层
DepartmentDao.java
package cn.imut.dao; import cn.imut.pojo.Department; import org.apache.ibatis.annotations.*; import java.util.List; public interface DepartmentDao { //部门删除员工(根据员工号) @Delete("delete from tbl_dept where dept_id = #{deptId}") int deleteDeptById(@Param("deptId") Integer deptId); //员工更换部门(员工号,所有信息) @Update("UPDATE tbl_dept SET dept_name = #{department.deptName, jdbcType = VARCHAR}, dept_leader = #{department.deptLeader, jdbcType = VARCHAR} WHERE dept_id = #{deptId}") int updateDeptById(@Param("deptId") Integer deptId, @Param("department") Department department); //员工加入部门 @Insert("insert into tbl_dept (dept_name, dept_leader) values (#{department.deptName}, #{department.deptLeader})") int insertDept(@Param("department") Department department); //根据id查询员工 @Select("select dept_id as 'deptId', dept_name as 'deptName', dept_leader as 'deptLeader' from tbl_dept where dept_id = #{deptId}") Department selectOneById(@Param("deptId") Integer deptId); //根据员工新名查询员工 @Select("select dept_id as 'deptId', dept_name as 'deptName', dept_leader as 'deptLeader' from tbl_dept where dept_leader = #{deptLeader}") Department selectOneByLeader(@Param("deptLeader") String deptLeader); //根据部门名称查询 @Select("select dept_id as 'deptId', dept_name as 'deptName', dept_leader as 'deptLeader' from tbl_dept where dept_name = #{deptName}") Department selectOneByName(@Param("deptName") String deptName); //查询所有部门中的员工 @Select("select dept_id as 'deptId', dept_name as 'deptName', dept_leader as 'deptLeader' from tbl_dept") List<Department> selectDeptList(); //分页查询,从前一个开始,显示后一个的条数 @Select("select dept_id as 'deptId', dept_name as 'deptName', dept_leader as 'deptLeader' FROM tbl_dept LIMIT #{offset}, #{limit}") List<Department> selectDeptsByLimitAndOffset(@Param("offset") Integer offset, @Param("limit") Integer limit); // @Select({"SELECT COUNT(dept_id) FROM tbl_dept WHERE dept_leader = #{deptLeader} OR dept_name = #{deptName}"}) int checkDeptsExistsByNameAndleader(@Param("deptLeader") String deptLeader, @Param("deptName") String deptName); //显示行数 @Select("select count(*) from tbl_dept") int countDepts(); }
EmployeeDao.java
package cn.imut.dao; import cn.imut.pojo.Employee; import org.apache.ibatis.annotations.*; import java.util.List; public interface EmployeeDao { //删除员工 @Delete("delete from tbl_emp where emp_id = #{empId}") int deleteOneById(@Param("empId") Integer empId); //修改员工信息 @Update("UPDATE tbl_emp SET emp_email = #{employee.empEmail, jdbcType = VARCHAR}, gender = #{employee.gender, jdbcType = VARCHAR}, department_id = #{employee.departmentId, jdbcType = INTEGER} WHERE emp_id = #{empId, jdbcType = INTEGER}") int updateOneById(@Param("empId") Integer empId, @Param("employee") Employee employee); //增加员工信息 @Insert("insert into tbl_emp (emp_name, emp_email, gender, department_id) values (#{empName}, #{empEmail}, #{gender}, #{departmentId})") int insertOne(Employee employee); //查询员工(工号查询) @Select("select emp_id empId, emp_name empName, emp_email empEmail, gender, department_id departmentId FROM tbl_emp WHERE emp_id = #{empId}") Employee selectOneById(@Param("empId") int empId); //查询员工(姓名查询) @Select("select emp_id empId, emp_name empName, emp_email empEmail, gender, department_id departmentId FROM tbl_emp WHERE emp_name = #{empName}") Employee selectOneByName(@Param("empName") String empName); //查询员工(包含部门信息) Employee selectWithDeptById(@Param("empId") Integer empId); //分页查询 limit:返回记录的最大行数 offset:返回记录行的偏移量 //offset = 10, limit = 5 时,从数据库第11行开始返回5条查询结果 //范围为 offset + 1 --------- offset + limit List<Employee> selectByLimitAndOffset(@Param("offset") Integer offset, @Param("limit") Integer limit); //查询总记录条数 @Select("select count(*) from tbl_emp;") int countEmps(); }
Service层
EmployeeServiceImpl.java
package cn.imut.service.impl; import cn.imut.dao.EmployeeDao; import cn.imut.pojo.Employee; import cn.imut.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeDao employeeDao; @Override public int deleteOneById(Integer empId) { return employeeDao.deleteOneById(empId); } @Override public int updateOneById(Integer empId, Employee employee) { return employeeDao.updateOneById(empId,employee); } @Override public int insertOne(Employee employee) { return employeeDao.insertOne(employee); } @Override public Employee selectOneById(int empId) { return employeeDao.selectOneById(empId); } @Override public Employee selectOneByName(String empName) { return employeeDao.selectOneByName(empName); } @Override public Employee selectWithDeptById(Integer empId) { return employeeDao.selectWithDeptById(empId); } @Override public List<Employee> selectByLimitAndOffset(Integer offset, Integer limit) { return employeeDao.selectByLimitAndOffset(offset,limit); } @Override public int countEmps() { return employeeDao.countEmps(); } }
DepartmentServiceImpl.java
package cn.imut.service.impl; import cn.imut.dao.DepartmentDao; import cn.imut.pojo.Department; import cn.imut.service.DepartmentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class DepartmentServiceImpl implements DepartmentService { @Autowired private DepartmentDao departmentDao; @Override public int deleteDeptById(Integer deptId) { return departmentDao.deleteDeptById(deptId); } @Override public int updateDeptById(Integer deptId, Department department) { return departmentDao.updateDeptById(deptId,department); } @Override public int insertDept(Department department) { return departmentDao.insertDept(department); } @Override public Department selectOneById(Integer deptId) { return departmentDao.selectOneById(deptId); } @Override public Department selectOneByLeader(String deptLeader) { return departmentDao.selectOneByLeader(deptLeader); } @Override public Department selectOneByName(String deptName) { return departmentDao.selectOneByName(deptName); } @Override public List<Department> selectDeptList() { return departmentDao.selectDeptList(); } @Override public List<Department> selectDeptsByLimitAndOffset(Integer offset, Integer limit) { return departmentDao.selectDeptsByLimitAndOffset(offset,limit); } @Override public int checkDeptsExistsByNameAndleader(String deptLeader, String deptName) { return departmentDao.checkDeptsExistsByNameAndleader(deptLeader,deptName); } @Override public int countDepts() { return departmentDao.countDepts(); } }
Controller层
LoginContext.java
package cn.imut.controller; import cn.imut.utils.JsonMsg; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; @Controller @RequestMapping(value = "/imut") public class LoginController { //登陆页面 @RequestMapping(value = "/login", method = RequestMethod.GET) public String login() { return "login"; } //登陆页面做判断 @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(); } //跳转到主页面 @RequestMapping(value = "/main", method = RequestMethod.GET) public String main() { return "main"; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout() { return "login"; } }
MainController.java
package cn.imut.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/imut") public class MainController { }
DepartmentController.java
package cn.imut.controller; import cn.imut.pojo.Department; import cn.imut.service.DepartmentService; import cn.imut.utils.JsonMsg; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.util.List; //部门 @Controller @RequestMapping(value = "/imut/dept") public class DepartmentController { @Autowired private DepartmentService departmentService; //部门删除员工 @RequestMapping(value = "delDept/{deptId}", method = RequestMethod.DELETE) @ResponseBody public JsonMsg deleteDept(@PathVariable("deptId") Integer deptId) { int res = 0; if(deptId > 0) { res = departmentService.deleteDeptById(deptId); } if(res != 1) { return JsonMsg.fail().addInfo("del_dept_error", "删除异常"); } return JsonMsg.success(); } //员工更换部门 @RequestMapping(value = "updateDept/{deptId}", method = RequestMethod.PUT) @ResponseBody public JsonMsg updateDeptById(@PathVariable("deptId") Integer deptId, Department department) { int res = 0; if(deptId > 0) { res = departmentService.updateDeptById(deptId,department); } if(res != 1) { return JsonMsg.fail().addInfo("update_dept_error", "更换部门失败"); } return JsonMsg.success(); } //增加部门 @RequestMapping(value = "/addDept", method = RequestMethod.PUT) @ResponseBody public JsonMsg addDept(Department department) { int res = departmentService.insertDept(department); if(res != 1) { return JsonMsg.fail().addInfo("add_dept_error", "增加部门异常"); } return JsonMsg.success(); } //查询部门信息总页码数 @RequestMapping(value = "/getTotalPages", method = RequestMethod.GET) @ResponseBody public JsonMsg getTotalPages() { //每页显示的记录行数 int limit = 5; //总记录数 int totalItem = departmentService.countDepts(); int temp = totalItem / limit; int totalPages = (totalItem % limit == 0) ? temp : temp + 1; return JsonMsg.success().addInfo("totalPages", totalPages); } //根据id查询部门 @RequestMapping(value = "/getDeptById/{deptId}", method = RequestMethod.GET) @ResponseBody public JsonMsg getDeptById(@PathVariable("deptId") Integer deptId){ Department department = null; if (deptId > 0){ department = departmentService.selectOneById(deptId); } if (department != null){ return JsonMsg.success().addInfo("department", department); } return JsonMsg.fail().addInfo("get_dept_error", "无部门信息"); } //分页查询:返回指定页数对应的数据 @RequestMapping(value = "/getDeptList", method = RequestMethod.GET) public ModelAndView getDeptList(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo){ ModelAndView mv = new ModelAndView("departmentPage"); //每页显示的记录行数 int limit = 5; //总记录数 int totalItems = departmentService.countDepts(); int temp = totalItems / limit; int totalPages = (totalItems % limit== 0) ? temp : temp+1; //每页的起始行(offset+1)数据,如第一页(offset=0,从第1(offset+1)行数据开始) int offset = (pageNo - 1)*limit; List<Department> departments = departmentService.selectDeptsByLimitAndOffset(offset,limit); mv.addObject("departments", departments) .addObject("totalItems", totalItems) .addObject("totalPages", totalPages) .addObject("curPageNo", pageNo); return mv; } //查询所有部门名称 @RequestMapping(value = "/getDeptName", method = RequestMethod.GET) @ResponseBody public JsonMsg getDeptName(){ List<Department> departmentList = departmentService.selectDeptList(); if (departmentList != null){ return JsonMsg.success().addInfo("departmentList", departmentList); } return JsonMsg.fail(); } }
EmployeeContriller.java
package cn.imut.controller; import cn.imut.pojo.Employee; import cn.imut.service.EmployeeService; import cn.imut.utils.JsonMsg; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller @RequestMapping(value = "/imut/emp") public class EmployeeController { @Autowired EmployeeService employeeService; //员工删除操作 @RequestMapping(value = "/deleteEmp/{empId}", method = RequestMethod.DELETE) @ResponseBody public JsonMsg deleteEmp(@PathVariable("empId") Integer empId){ int res = 0; if (empId > 0){ res = employeeService.deleteOneById(empId); } if (res != 1){ return JsonMsg.fail().addInfo("emp_del_error", "员工删除异常"); } return JsonMsg.success(); } //更改员工信息 @RequestMapping(value ="/updateEmp/{empId}", method = RequestMethod.PUT) @ResponseBody public JsonMsg updateEmp(@PathVariable("empId") Integer empId, Employee employee){ int res = employeeService.updateOneById(empId, employee); if (res != 1){ return JsonMsg.fail().addInfo("emp_update_error", "更改异常"); } return JsonMsg.success(); } //查询输入的员工姓名是否重复 @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.selectOneByName(empName); if (employee != null){ return JsonMsg.fail().addInfo("name_reg_error", "用户名重复"); }else { return JsonMsg.success(); } } //新增记录后,查询最新的页数 @RequestMapping(value = "/getTotalPages", method = RequestMethod.GET) @ResponseBody public JsonMsg getTotalPage(){ int totalItems = employeeService.countEmps(); //获取总的页数 int temp = totalItems / 5; int totalPages = (totalItems % 5 == 0) ? temp : temp+1; return JsonMsg.success().addInfo("totalPages", totalPages); } //新增员工 @RequestMapping(value = "/addEmp", method = RequestMethod.POST) @ResponseBody public JsonMsg addEmp(Employee employee){ int res = employeeService.insertOne(employee); if (res == 1){ return JsonMsg.success(); }else { return JsonMsg.fail(); } } //根据id查询员工信息 @RequestMapping(value = "/getEmpById/{empId}", method = RequestMethod.GET) @ResponseBody public JsonMsg getEmpById(@PathVariable("empId") Integer empId){ Employee employee = employeeService.selectOneById(empId); if (employee != null){ return JsonMsg.success().addInfo("employee", employee); }else { return JsonMsg.fail(); } } //查询指定页码包含的数据 @RequestMapping(value = "/getEmpList", method = RequestMethod.GET) public ModelAndView getEmp(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo){ ModelAndView mv = new ModelAndView("employeePage"); 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.selectByLimitAndOffset(offset, limit); //获取总的记录数 int totalItems = employeeService.countEmps(); //获取总的页数 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; } }
前端略
来源:https://www.cnblogs.com/yfyyy/p/12433616.html