效果如下:能实现多条件查询加分页、添加、修改、删除及批量删除
此界面仅供参考
列表页面:
添加页面:
修改页面:
数据库:MySQL
/*
SQLyog Ultimate v8.3
MySQL - 5.5.56 : Database - employeemanager
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`employeemanager` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `employeemanager`;
/*Table structure for table `department` */
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`deptno` int(11) NOT NULL,
`dname` varchar(50) DEFAULT NULL,
`loc` varchar(50) DEFAULT NULL,
PRIMARY KEY (`deptno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `department` */
insert into `department`(`deptno`,`dname`,`loc`) values (10,'教研部','北京'),(20,'学工部','上海'),(30,'销售部','广州'),(40,'财务部','武汉');
/*Table structure for table `employee` */
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`empno` int(11) NOT NULL AUTO_INCREMENT,
`ename` varchar(50) DEFAULT NULL,
`job` varchar(50) DEFAULT NULL,
`hiredate` date DEFAULT NULL,
`sal` decimal(7,2) DEFAULT NULL,
`comm` decimal(7,2) DEFAULT NULL,
`deptno` int(11) DEFAULT NULL,
PRIMARY KEY (`empno`),
KEY `fk_dept` (`deptno`),
CONSTRAINT `fk_dept` FOREIGN KEY (`deptno`) REFERENCES `department` (`deptno`)
) ENGINE=InnoDB AUTO_INCREMENT=1016 DEFAULT CHARSET=utf8;
/*Data for the table `employee` */
insert into `employee`(`empno`,`ename`,`job`,`hiredate`,`sal`,`comm`,`deptno`) values (1002,'戴绮丝','销售员','2014-02-20','16000.00','3000.00',30),(1003,'殷天正','销售员','2013-02-22','12500.00','5000.00',30),(1004,'刘备','经理','2010-04-02','29750.00',NULL,20),(1005,'谢逊','销售员','2011-09-28','12500.00','14000.00',30),(1006,'关羽','经理','2012-05-01','28500.00',NULL,30),(1007,'张飞','经理','2015-09-01','24500.00',NULL,10),(1008,'诸葛亮','分析师','2009-04-19','30000.00',NULL,20),(1009,'曾阿牛','董事长','2008-11-17','50000.00',NULL,10),(1010,'韦一笑','销售员','2010-09-28','15000.00','0.00',30),(1011,'周泰','文员','2018-05-23','11000.00',NULL,20),(1012,'程普','文员','2015-12-03','9500.00',NULL,30),(1013,'庞统','分析师','2017-12-03','30000.00',NULL,20),(1014,'黄盖','文员','2017-01-23','13000.00',NULL,10),(1015,'aa','hjhj','2020-04-14','1212.00','12.00',20);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
代码实现:
项目结构如下:
xml报错不影响项目最终运行结果。
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ruanyuan</groupId>
<artifactId>CRUD</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>CRUD Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!-- 配置jar包 -->
<dependencies>
<!--servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1.3-b06</version>
<scope>provided</scope>
</dependency>
<!-- 导入jstl 标签库 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 导入json -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
<!-- 配置mysql数据库 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.1</version>
</dependency>
<!--mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--log4j-core -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
</dependencies>
</project>
src/main/java文件夹下:
实体类实现:
Department实体类
package com.ssm.pojo;
/**
* 部门实体类
* @author
*
*/
public class Department {
//部门编号
private int deptno;
//部门名称
private String dname;
//部门所在地
private String ioc;
/**
* 添加对应属性的setter/getter方法
* @return
*/
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getIoc() {
return ioc;
}
public void setIoc(String ioc) {
this.ioc = ioc;
}
/**
* 生成有参构造
* @param deptno
* @param dname
* @param ioc
*/
public Department(int deptno, String dname, String ioc) {
super();
this.deptno = deptno;
this.dname = dname;
this.ioc = ioc;
}
/**
* 生成无参构造
*/
public Department() {
super();
}
/**
* 重写toString方法
*/
@Override
public String toString() {
return "Department [deptno=" + deptno + ", dname=" + dname + ", ioc=" + ioc + "]";
}
}
Employee实体类
package com.ssm.pojo;
/**
* 员工实体类
* @author
*
*/
public class Employee {
//员工编号
private int empno;
//员工姓名
private String ename;
//职位
private String job;
//入职日期
private String hiredate;
//薪水
private int sal;
//奖金
private int comm;
//所在部门
private Department department;
/**
* 生成对应属性的setter/getter方法
* @return
*/
public String getHiredate() {
return hiredate;
}
public void setHiredate(String hiredate) {
this.hiredate = hiredate;
}
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
public int getComm() {
return comm;
}
public void setComm(int comm) {
this.comm = comm;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
/**
* 生成有参构造
* @param empno
* @param ename
* @param job
* @param hiredate
* @param sal
* @param comm
* @param department
*/
public Employee(int empno, String ename, String job, String hiredate, int sal, int comm, Department department) {
super();
this.empno = empno;
this.ename = ename;
this.job = job;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.department = department;
}
/**
* 生成无参构造
*/
public Employee() {
super();
}
/**
* 重写toString方法
*/
@Override
public String toString() {
return "Employee [empno=" + empno + ", ename=" + ename + ", job=" + job + ", hiredate=" + hiredate + ", sal="
+ sal + ", comm=" + comm + ", department=" + department + "]";
}
}
分页实体类:
package com.ssm.pojo;
import java.util.List;
/**
* 分页实体类
* @author
*
* @param
*/
public class PageBean<T> {
//当前页数
private int currPage;
//每页几条数据
private int pageSize;
//总记录数
private int totalCount;
//总页数
private int totalPage;
//集合
private List<T> lists;
/**
* 添加对应属性的setter/getter方法
* @return
*/
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getLists() {
return lists;
}
public void setLists(List<T> lists) {
this.lists = lists;
}
/**
* 生成有参构造
* @param currPage
* @param pageSize
* @param totalCount
* @param totalPage
* @param lists
*/
public PageBean(int currPage, int pageSize, int totalCount, int totalPage, List<T> lists) {
super();
this.currPage = 1;
this.pageSize = pageSize;
this.totalCount = totalCount;
this.totalPage = totalPage;
this.lists = lists;
}
/**
* 生成无参构造
*/
public PageBean() {
super();
this.currPage = 1;
}
/**
* 重写toString方法
*/
@Override
public String toString() {
return "PageBean [currPage=" + currPage + ", pageSize=" + pageSize + ", totalCount=" + totalCount
+ ", totalPage=" + totalPage + ", lists=" + lists + "]";
}
}
数据访问层实现:
DepartmentDao:
package com.ssm.dao;
import java.util.List;
import com.ssm.pojo.Department;
/**
* 部门数据访问层接口
* @author
*
*/
public interface DepartmentDao {
/**
* 查询所有部门信息
* @return
*/
public List<Department> getAllDepartment();
}
DeaprtmentDao.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="com.ssm.dao.DepartmentDao">
<!-- 查询所有部门信息 -->
<select id="getAllDepartment" resultType="department">
select * from department
</select>
</mapper>
EmployeeDao
package com.ssm.dao;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.ssm.pojo.Employee;
/**
* 员工数据访问层接口
* @author
*
*/
public interface EmployeeDao {
/**
* 根据员工编号查询员工信息
* @param empno
* @return
*/
public Employee getEmployeeByEmpno(int empno);
/**
* 添加员工信息
* @param employee
* @return
*/
public int addEmployee(Employee employee);
/**
* 修改员工信息
* @param employee
* @return
*/
public int updateEmployee(Employee employee);
/**
* 根据员工编号删除员工信息
* @param empno
* @return
*/
public int deleteEmployee(int empno);
/**
* 批量删除员工信息
* @param empno
* @return
*/
public int deleteEmployees(List<Integer> empno);
/**
* 多条件查询符合条件的员工信息个数
* @param deptno
* @param ename
* @param hiredate1
* @param hiredate2
* @param sal1
* @param sal2
* @return
*/
public int getEmployeeCountBySearch(@Param("deptno") Integer deptno,@Param("ename")String ename,@Param("hiredate1")String hiredate1,@Param("hiredate2")String hiredate2,@Param("sal1")String sal1,@Param("sal2")String sal2);
/**
* 多条件查询符合条件的员工信息
* @param map
* @param deptno
* @param ename
* @param hiredate1
* @param hiredate2
* @param sal1
* @param sal2
* @return
*/
List<Employee> findByPageBySearch(@Param("map") HashMap<String,Object> map,@Param("deptno") Integer deptno,@Param("ename")String ename,@Param("hiredate1")String hiredate1,@Param("hiredate2")String hiredate2,@Param("sal1")String sal1,@Param("sal2")String sal2);
}
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="com.ssm.dao.EmployeeDao">
<resultMap type="employee" id="employeeResult">
<id property="empno" column="empno" />
<result property="ename" column="ename" />
<result property="job" column="job" />
<result property="hiredate" column="hiredate" />
<result property="sal" column="sal" />
<result property="comm" column="comm" />
<association property="department" javaType="department">
<id property="deptno" column="deptno" />
<result property="dname" column="dname" />
<result property="ioc" column="ioc" />
</association>
</resultMap>
<!-- 根据员工编号查询员工信息 -->
<select id="getEmployeeByEmpno" resultMap="employeeResult"
parameterType="Integer">
select * from employee where empno=#{empno}
</select>
<!-- 添加员工信息 -->
<insert id="addEmployee" parameterType="employee">
INSERT INTO employee
VALUES
(null,#{ename},#{job},now(),#{sal},#{comm},#{department.deptno})
</insert>
<!-- 修改员工信息 -->
<update id="updateEmployee" parameterType="employee">
update employee set
ename=#{ename},job=#{job},sal=#{sal},comm=#{comm},deptno=#{department.deptno}
WHERE empno = #{empno} ;
</update>
<!-- 删除员工信息 -->
<delete id="deleteEmployee" parameterType="Integer">
delete from employee WHERE empno = #{empno}
</delete>
<!-- 批量删除员工信息 -->
<delete id="deleteEmployees" parameterType="list">
delete from employee where empno in
<foreach item="empno" index="index" collection="list" open="("
separator="," close=")">
#{empno}
</foreach>
</delete>
<!-- 多条件查询符合条件的员工信息个数 -->
<select id="getEmployeeCountBySearch" resultType="Integer">
SELECT count(*) FROM employee e INNER JOIN department d WHERE
e.deptno=d.deptno
<if test="deptno!=null and deptno!=-1">
and e.deptno=#{deptno}
</if>
<if test="ename!=null and ename!=''">
and ename like concat('%',#{ename},'%')
</if>
<if test="hiredate1!=null and hiredate1!=''">
and hiredate >=#{hiredate1}
</if>
<if test="hiredate2!=null and hiredate2!=''">
and hiredate <=#{hiredate2}
</if>
<if test="sal1!=null and sal1!=''">
and (sal+IFNULL(comm,0)) >=#{sal1}
</if>
<if test="sal2!=null and sal2!=''">
and (sal+IFNULL(comm,0)) <=#{sal2}
</if>
</select>
<!-- 多条件查询符合条件的员工信息 -->
<select id="findByPageBySearch" resultMap="employeeResult">
SELECT empno,ename,job,hiredate,(sal+IFNULL(comm,0)) AS
sal,d.dname,d.loc FROM employee e INNER JOIN department d WHERE
e.deptno=d.deptno
<if test="deptno!=null and deptno!=-1">
and e.deptno=#{deptno}
</if>
<if test="ename!=null and ename!=''">
and ename like concat('%',#{ename},'%')
</if>
<if test="hiredate1!=null and hiredate1!=''">
and hiredate >=#{hiredate1}
</if>
<if test="hiredate2!=null and hiredate2!=''">
and hiredate <=#{hiredate2}
</if>
<if test="sal1!=null and sal1!=''">
and (sal+IFNULL(comm,0)) >=#{sal1}
</if>
<if test="sal2!=null and sal2!=''">
and (sal+IFNULL(comm,0)) <=#{sal2}
</if>
order by empno asc
<if test="map!=null">
limit #{map.start},#{map.size}
</if>
</select>
</mapper>
业务逻辑层实现:
DepartmentService
package com.ssm.service;
import java.util.List;
import com.ssm.pojo.Department;
/**
* 部门业务逻辑层接口
* @author
*
*/
public interface DepartmentService {
/**
* 查询所有部门信息
* @return
*/
public List<Department> getAllDepartment();
}
DepartmentServiceImpl
package com.ssm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ssm.dao.DepartmentDao;
import com.ssm.pojo.Department;
import com.ssm.service.DepartmentService;
/**
* 部门业务逻辑层接口实现类
* @author
*
*/
@Service
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentDao departmentDao;
/**
* 查询所有部门信息
*/
public List<Department> getAllDepartment() {
// TODO Auto-generated method stub
return departmentDao.getAllDepartment();
}
}
EmployeeService
package com.ssm.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.ssm.pojo.Employee;
import com.ssm.pojo.PageBean;
/**
* 员工业务逻辑层接口
* @author
*
*/
public interface EmployeeService {
/**
* 根据员工编号查询员工信息
* @param empno
* @return
*/
public Employee getEmployeeByEmpno(int empno);
/**
* 添加员工信息
* @param employee
* @return
*/
public int addEmployee(Employee employee);
/**
* 修改员工信息
* @param employee
* @return
*/
public int updateEmployee(Employee employee);
/**
* 根据员工编号删除员工信息
* @param empno
* @return
*/
public int deleteEmployee(int empno);
/**
* 批量删除员工信息
* @param empno
* @return
*/
public int deleteEmployees(List<Integer> empno);
/**
* 多条件查询符合条件的员工信息个数
* @param deptno
* @param ename
* @param hiredate1
* @param hiredate2
* @param sal1
* @param sal2
* @return
*/
public int getEmployeeCountBySearch(@Param("deptno") Integer deptno,@Param("ename")String ename,@Param("hiredate1")String hiredate1,@Param("hiredate2")String hiredate2,@Param("sal1")String sal1,@Param("sal2")String sal2);
/**
* 多条件查询符合条件的员工信息
* @param map
* @param deptno
* @param ename
* @param hiredate1
* @param hiredate2
* @param sal1
* @param sal2
* @return
*/
public PageBean<Employee> findByPageBySearch(@Param("currentPage") int currentPage,@Param("deptno") Integer deptno,@Param("ename")String ename,@Param("hiredate1")String hiredate1,@Param("hiredate2")String hiredate2,@Param("sal1")String sal1,@Param("sal2")String sal2);
}
EmployeeServiceImpl
package com.ssm.service.impl;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ssm.dao.EmployeeDao;
import com.ssm.pojo.Employee;
import com.ssm.pojo.PageBean;
import com.ssm.service.EmployeeService;
/**
* 员工业务逻辑层接口实现类
* @author
*
*/
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeDao employeeDao;
/**
* 根据员工编号查询员工信息
*/
public Employee getEmployeeByEmpno(int empno) {
return employeeDao.getEmployeeByEmpno(empno);
}
/**
* 添加员工信息
*/
public int addEmployee(Employee employee) {
return employeeDao.addEmployee(employee);
}
/**
* 修改员工信息
*/
public int updateEmployee(Employee employee) {
return employeeDao.updateEmployee(employee);
}
/**
* 删除员工信息
*/
public int deleteEmployee(int empno) {
return employeeDao.deleteEmployee(empno);
}
/**
* 批量删除员工信息
*/
public int deleteEmployees(List<Integer> empno) {
return employeeDao.deleteEmployees(empno);
}
/**
* 多条件查询符合条件的员工信息个数
*/
public int getEmployeeCountBySearch(Integer deptno, String ename,
String hiredate1, String hiredate2, String sal1, String sal2) {
return employeeDao.getEmployeeCountBySearch(deptno, ename, hiredate1, hiredate2, sal1, sal2);
}
/**
* 多条件查询符合条件的员工信息
* @param currentPage
* @param deptno
* @param ename
* @param hiredate1
* @param hiredate2
* @param sal1
* @param sal2
* @return
*/
public PageBean<Employee> findByPageBySearch(int currentPage,
Integer deptno, String ename, String hiredate1, String hiredate2,
String sal1, String sal2) {
//创建hashmap集合
HashMap<String,Object> map = new HashMap<String,Object>();
//创建员工分页实体类
PageBean<Employee> pageBean = new PageBean<Employee>();
//为当前页数赋值
pageBean.setCurrPage(currentPage);
//初始化每页记录数
int pageSize=5;
//为每个记录数赋值
pageBean.setPageSize(pageSize);
//查询符合条件的员工个数
int totalCount =employeeDao.getEmployeeCountBySearch(deptno, ename, hiredate1, hiredate2, sal1, sal2);
//为总记录数赋值
pageBean.setTotalCount(totalCount);
double tc=totalCount;
Double num=Math.ceil(tc/pageSize);
//为总页数赋值
pageBean.setTotalPage(num.intValue());
//map集合中存放当前页数和每页存放的记录数
map.put("start",(currentPage-1)*pageSize);
map.put("size", pageBean.getPageSize());
//查询符合条件的员工信息
List<Employee> lists = employeeDao.findByPageBySearch(map, deptno, ename, hiredate1, hiredate2, sal1, sal2);
//为员工分页实体类集合属性赋值
pageBean.setLists(lists);
return pageBean;
}
}
业务逻辑实现:
package com.ssm.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ssm.pojo.Department;
import com.ssm.pojo.Employee;
import com.ssm.pojo.PageBean;
import com.ssm.service.DepartmentService;
import com.ssm.service.EmployeeService;
/**
* 员工实体类控制层
* @author
*
*/
@Controller
public class EmployeeController {
@Autowired
private EmployeeService empoloyeeService;
@Autowired
private DepartmentService departmentService;
/**
* 跳转到员工系统页面
* @param model
* @return
*/
@RequestMapping("/toList")
public String toList(Model model,HttpServletRequest request,@RequestParam(value = "currPage",required = true,defaultValue = "1")int currPage,@RequestParam(value = "deptno",required = false,defaultValue = "-1")String deptno,
@RequestParam(value = "ename",required = false,defaultValue = "")String ename,@RequestParam(value = "hiredate1",required = false,defaultValue = "")String hiredate1,@RequestParam(value = "hiredate2",required = false,defaultValue = "")String hiredate2,
@RequestParam(value = "sal1",required = false,defaultValue = "")String sal1,@RequestParam(value = "sal2",required = false,defaultValue = "")String sal2){
//查询所有部门信息
List<Department> departments=departmentService.getAllDepartment();
model.addAttribute("departments", departments);
//查询符合条件的员工信息
PageBean<Employee> pagemsg=empoloyeeService.findByPageBySearch(currPage, Integer.valueOf(deptno), ename, hiredate1, hiredate2, sal1, sal2);
//拼接路径
String url=request.getContextPath()+"/toList?deptno="+deptno+"&ename="+ename+"&hiredate1="+hiredate1+"&hiredate2="+hiredate2+"&sal1="+sal1+"&sal2="+"&";
model.addAttribute("list", pagemsg);
model.addAttribute("url", url);
model.addAttribute("deptno", deptno);
model.addAttribute("ename", ename);
model.addAttribute("hiredate1", hiredate1);
model.addAttribute("hiredate2", hiredate2);
model.addAttribute("sal1", sal1);
model.addAttribute("sal2", sal2);
List<Employee> employees=pagemsg.getLists();
model.addAttribute("employees", employees);
return "AllEmployee";
}
/**
* 添加之前 修改之前
* @param model
* @param request
* @return
*/
@RequestMapping("/toEdit")
public String toEdit(Model model,String details,String empno){
if(details.equals("update")){
Employee employee=empoloyeeService.getEmployeeByEmpno(Integer.valueOf(empno));
model.addAttribute("employee", employee);
}
List<Department> departments=departmentService.getAllDepartment();
model.addAttribute("departments", departments);
return "addEmployee";
}
/**
* 添加员工信息的保存操作
* @param request
* @return
*/
@RequestMapping("/addEmp")
public String addEmployee(Employee employee){
empoloyeeService.addEmployee(employee);
return "redirect:/toList";
}
/**
* 修改员工信息的保存操作
* @param request
* @return
*/
@RequestMapping("/updateEmployee")
public String updateEmployee(Employee employee){
empoloyeeService.updateEmployee(employee);
return "redirect:/toList";
}
/**
* 单个删除员工信息
* @param request
*/
@RequestMapping("/deleteEmployee")
public String deleteEmployee(int empno){
empoloyeeService.deleteEmployee(empno);
return "redirect:/toList";
}
/**
*批量删除员工信息
* @param request
* @return
*/
@RequestMapping("/del")
@ResponseBody
public String del(String ids){
//int类型数组:存放员工编号,以“,”分割
int[] ids2 = Arrays.stream(ids.split(",")).mapToInt(s -> Integer.parseInt(s)).toArray();
//创建存放员工编号的集合
List<Integer> empnos=new ArrayList<Integer>();
for (int i = 0; i < ids2.length; i++) {
empnos.add(ids2[i]);
}
int count=empoloyeeService.deleteEmployees(empnos);
return String.valueOf(count);
}
}
src/main/resources文件夹下:
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/EmployeeManager?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5
log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR,stdout
# MyBatis logging configuration...
log4j.logger.com.ssm=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 定义别名 -->
<typeAliases>
<package name="com.ssm.pojo"/>
</typeAliases>
</configuration>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 读取数据库文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<!-- 数据库驱动 -->
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxTotal" value="${jdbc.maxTotal}"/>
<property name="maxIdle" value="${jdbc.maxIdle}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
</bean>
<!-- 事务管理器,依赖于数据源 -->
<bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 开启事物注解 -->
<tx:annotation-driven transaction-manager="transactionManger"/>
<!-- 配置MyBatis工厂SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 制定MyBatis核心配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 配置mapper扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao"/>
</bean>
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.ssm.service"/>
</beans>
springmvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置包扫描器,扫描Controller注解的类 -->
<context:component-scan base-package="com.ssm.controller"/>
<!-- 加载注解驱动 -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:default-servlet-handler/>
</beans>
src/main/webapp文件夹下:
AllEmployee.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>员工列表信息</title>
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/jquery.js"></script>
<script type="text/javascript">
function del() {
var result= confirm("你确定删除吗?");
if(result==true){
var arr = [];
$("input:checkbox[name='empno']:checked").each(function(i){
arr.push($(this).val());
});
if(arr.length==0){
alert("请先选中要删除的行");
}
$.ajax({
url:"${pageContext.request.contextPath }/del?ids="+arr,
type:"post",
success:function(data){
if(data>0){
alert("删除成功");
window.location.href="${pageContext.request.contextPath}/toList";
}else{
alert("删除失败");
}
}
});
}
}
function check(){
var hiredate1=$("#hiredate1").val();
var hiredate2=$("#hiredate2").val();
if(hiredate1!="" && hiredate2!="" && hiredate1>=hiredate2){
alert("开始时间不能大于或等于结束时间,请重新选择");
$("#hiredate2").val("");
}
var sal1=parseInt($("#sal1").val());
var sal2=parseInt($("#sal2").val());
if(sal1!="" && sal2!="" && sal1>=sal2){
alert("开始金额不能大于或等于结束金额,请重新输入");
$("#sal2").val("");
}
}
$(document).ready(function(){
$("#empnos").click(function(){
$('[name=empno]:checkbox').attr("checked",this.checked);
});
});
</script>
</head>
<body>
<h2>员工信息列表</h2>
<form action="${pageContext.request.contextPath }/toList" method="post">
查询条件:部门:<select name="deptno" id="deptno">
<option value="-1">请选择</option>
<c:forEach items="${departments }" var="dept">
<option value="${dept.deptno}" ${(dept.deptno)==deptno?'selected':''}>${dept.dname }</option>
</c:forEach>
</select> 姓名:<input type="text" name="ename" value="${ename}" id="ename">
入职日期:<input type="date" name="hiredate1" value="${hiredate1 }"
id="hiredate1">-- <input type="date" name="hiredate2"
value="${hiredate2 }" id="hiredate2">
工资:<input type="number" name="sal1" value="${sal1 }" id="sal1" min="1">--
<input type="number" name="sal2" value="${sal2 }" id="sal2" min="1">
<input type="submit" value="查询" onclick="check()"> <a
href="${pageContext.request.contextPath }/toList">查询所有</a>
</form>
<a href="${pageContext.request.contextPath }/toEdit?details=add">添加员工信息</a>
<br>
<br>
<input type="button" value="批量删除" onclick="del()">
<table border="1" class="box">
<thead>
<tr>
<th><input type="checkbox" name="empnos" id="empnos">全选</th>
<th>员工编号</th>
<th>员工姓名</th>
<th>员工职位</th>
<th>雇佣日期</th>
<th>工资</th>
<th>所属部门</th>
<th>编辑</th>
</tr>
<c:choose>
<c:when test="${fn:length(employees)>0}">
<c:forEach items="${employees}" var="employee">
<tr>
<td><input type="checkbox" name="empno" value="${employee.empno }"></td>
<td>${employee.empno }</td>
<td>${employee.ename }</td>
<td>${employee.job }</td>
<td>${employee.hiredate }</td>
<td>${employee.sal }</td>
<td>${employee.department.dname }</td>
<td><a
href="${pageContext.request.contextPath }/toEdit?details=update&empno=${employee.empno }">修改</a>
<a onclick="javascripts:var result=confirm('你确定删除吗?');if(result==true){window.location.href='${pageContext.request.contextPath }/deleteEmployee?empno=${employee.empno }'}"
>删除</a></td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
<tr>
<td colspan="9">抱歉,暂无员工信息</td>
</tr>
</c:otherwise>
</c:choose>
</thead>
</table>
<c:if test="${fn:length(employees)>0}">
<span id="page"><jsp:include page="page.jsp"/></span>
</c:if>
</body>
</html>
addEmployee.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>员工编辑</title>
</head>
<body>
<h3>${employee==null?'添加':'修改'}员工</h3>
<form action="${pageContext.request.contextPath}${employee==null?'/addEmp':'/updateEmployee'}" method="post">
<input type="hidden" name="empno" id="empno" value="${employee==null?0:employee.empno}" />
<table border="1px">
<tr>
<td> 员工姓名:</td>
<td><input type="text" name="ename" value="${employee.ename }"></td>
</tr>
<tr>
<td> 员工职位:</td>
<td><input type="text" name="job" value="${employee.job }"></td>
</tr>
<tr>
<td> 薪水:</td>
<td><input type="number" name="sal" value="${employee.sal }" min="0"></td>
</tr>
<tr>
<td> 奖金:</td>
<td><input type="number" name="comm" value="${employee.comm }" min="0"></td>
</tr>
<tr>
<td> 所在部门:</td>
<td><select name="department.deptno" id="deptno">
<c:forEach items="${departments }" var="dept">
<option value="${dept.deptno}" ${(dept.deptno)==(employee.department.deptno)?'selected':''}>${dept.dname }</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
page.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<title>Insert title here</title>
</head>
<body>
<ul class="pagination">
<li><a href="${url }currPage${1 }">«</a></li>
<c:choose>
<c:when test="${list.currPage==1 }">
<li class = "disabled"><a href="#">上一页</a></li>
</c:when>
<c:otherwise>
<li><a href="${url }currPage=${list.currPage-1 }" >上一页</a></li>
</c:otherwise>
</c:choose>
<!-- 遍历输出页数 -->
<c:forEach var = "i" begin="1" end = "${list.totalPage }" step = "1">
<c:choose>
<c:when test="${i==list.currPage}">
<li class = "active"><a href="#">${i }</a></li>
</c:when>
<c:otherwise>
<c:choose>
<c:when test="${i>2 && i>
<c:if test="${i-1 == 2 || i+1==list.totalPage-1 && (list.currPage != 1 && list.currPage!=list.totalPage)}">
<li> <a href = "">...</a></li>
</c:if>
</c:when>
<c:otherwise>
<li><a href="${url }currPage=${i }">${i }</a></li>
</c:otherwise>
</c:choose>
</c:otherwise>
</c:choose>
</c:forEach>
<c:choose>
<c:when test="${list.currPage==list.totalPage }">
<li class="disabled"><a href="#">下一页</a></li>
</c:when>
<c:otherwise>
<li><a href="${url }currPage=${list.currPage+1 }">下一页</a></li>
</c:otherwise>
</c:choose>
<li><a
href="${url }currPage=${list.totalPage }" >»</a></li>
</ul>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>Login</display-name>
<!-- 配置加载Spring文件的监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<!-- 配置Spring MVC前端核心控制器 -->
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!-- 初始化时加载配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-config.xml</param-value>
</init-param>
<!-- 表示容器在启动时立即加载Servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<!-- 配置编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*
/toList